I'm trying to get my Windows Phone 7 Mango app to listen to incoming UDP packets but having a heck of a time. I have the new Beta 2 refresh of the Windows Phone 7.1 SDK and dev tools installed. Any deviation I try from this MSDN sample results in a SocketException 10022, "An invalid argument was supplied".
My code is pasted below. I have been trying to adapt the code I found on this stackoverflow post but to no avail. This line generates the exception when its reached:
synchronous = m_udpSock.ReceiveFromAsync(udpRecvArg);
I'm hoping someone here can help identify what's going wrong. I'm calling "StartUnicastListen()" when the user presses a button. m_udpSock is previously defined as a class variable and set to null. Per the "Remarks" section of the ReceiveFromAsync() MSDN page, I've set all of the required properties and events.
private void StartUnicastListen()
{
m_udpSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
SocketAsyncEventArgs udpRecvArg = new SocketAsyncEventArgs();
udpRecvLoopStart(udpRecvArg);
}
private void udpRecvLoopStart(SocketAsyncEventArgs udpRecvArg)
{
byte[] udpRecvBuffer = new byte[2048];
udpRecvArg.SetBuffer(udpRecvBuffer, 0, udpRecvBuffer.Length);
udpRecvArg.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 11100);
udpRecvArg.Completed += new EventHandler<SocketAsyncEventArgs>(udpRecvArg_Completed);
udpRecv(udpRecvArg);
}
private void udpRecv(SocketAsyncEventArgs udpRecvArg)
{
bool synchronous = false;
try {
synchronous = m_udpSock.ReceiveFromAsync(udpRecvArg);
} catch (SocketException e) {
Log("recvUdp()\n" + e.SocketErrorCode + "\n" + e.ToString(), false);
return;
} if (synchronous)
udpRecvArg_Completed(this, udpRecvArg);
}
void udpRecvArg_Completed(object sender, SocketAsyncEventArgs udpRecvArg) {
EndPoint udpEp = udpRecvArg.RemoteEndPoint;
string msg = Encoding.UTF8.GetString(udpRecvArg.Buffer, udpRecvArg.Offset, udpRecvArg.BytesTransferred);
Log(udpEp + " " + msg,false);
udpRecv(udpRecvArg);
}
There's such limited documentation the proper usage of ReceiveFromAsync()--which seems to be the only option for this on WP7--and on System.Net.Sockets in Windows Phone 7 in general right now.
Thanks in advance for any help you can provide.