UDP comm problem when switching from Sync to Async
I have a simple C#/.NET 3.5 client/server apps I am trying to write to get a handle on how to communicate in UDP. I am able to get the sync methods working and sending data back and forth, but now I am trying to switch to the async methods and I keep getting the error, "The requested address is not valid in it's context."
My Client code is as follows:
IPEndPoint ipep = new IPEndPoint(ipaddr, ipport);
newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
EndPoint remote1 = (EndPoint)ipep;
AddMessage("Looking for connections");
byte[] strt = Encoding.ASCII.GetBytes("open");
newsock.SendTo(strt,remote1);//.BeginSendTo(strt, 0, strt.Length, SocketFlags.None, remote1, new AsyncCallback(OnSend), null);
IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
EndPoint epSender = (EndPoint)ipeSender;
newsock.ReceiveFrom(rcv, ref epSender);
My Server is more complicated, as I have already switched to Async communicat开发者_运维技巧ion.
In a worker thread I call:
try
{
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint remote = (EndPoint)sender;
AddMessage("Beginning Wait for connections");
newsock.BeginReceiveFrom(rcv, 0, rcv.Length, SocketFlags.None, ref remote, new AsyncCallback(OnReceive), null);
while (true)
{
if (pleasestop.WaitOne(20))
break;
ts = DateTime.Now - lastnoop;
if (senddata)
{
//...fill sending byte array...
IPEndPoint ipep = new IPEndPoint(IPAddress.Any,0);//ipaddr, ipport);
EndPoint remote1 = (EndPoint)ipep;
newsock.BeginSendTo(sending, 0, sending.Length, SocketFlags.None, remote1, new AsyncCallback(OnSend), null);
}
}
In my OnSend callback function is where I get the error: "The requested address is not valid in it's context."
private void OnSend(IAsyncResult ar)
{
try
{
newsock.EndSendTo(ar);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n" + ex.StackTrace, "Server Send Error");
}
}
I dont think the object state can be null, try this:
newsock.BeginSendTo(sending, 0, sending.Length, SocketFlags.None,
remote1, new AsyncCallback(OnSend), newsock);
I found my problem. I wasn't using the correct EndPoint in my server to send a response back to my client.
In my receive callbackup function I now use mySender, which is a SendPoint defined at the class level. I then use this to send a response back to my client.
newsock.EndReceiveFrom(ar, ref mySender);
newsock.BeginSendTo(sending, 0, sending.Length, SocketFlags.None, mySender, new AsyncCallback(OnSend), mySender);
My app is now working correctly.
精彩评论