Search code examples
windows-store-appswindows-store

Windows Store app (Win 8.1) : Reading the UDP response using DatagramSocket


In a non-Windows-Store .Net app, I send a UDP request and synchronously read its response (using System.Net.Sockets classes) as follows:

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(endPoint);
socket.Send(byteArray);
socket.Receive(byteArray);

Now, I am trying to do the same thing in a Windows Store app - Windows 8.1 (using Windows.Networking.Sockets's DatagramSocket class):

DatagramSocket udpSocket = new DatagramSocket();
udpSocket.MessageReceived += SocketOnMessageReceived;
await udpSocket.ConnectAsync(new HostName(server), port);
var udpWriter = new DataWriter(udpSocket.OutputStream);
udpWriter.WriteBytes(msgBytes); // send the msg
await udpWriter.StoreAsync();

The issue I am facing is that the event handler "SocketOnMessageReceived" is never invoked. What have I missed?

I have enabled the capability "Private Networks (Client & Server)" currently. When I try the same code with capability "Internet (Client & Server)", the app crashes.

I am not a networking-concepts expert and I am new to Windows Store app development and can, very appreciatively, use some guidance here.

Thanks.


Solution

  • SOLVED! Had to debug the cause of crash. Turns out that when I received the UDP message, I was firing an app-level event, and that was crashing because I was not firing the event on the UI thread. The error reports / crash dumps from the windows 8.1 device were not showing this information, and hence kept getting confused about what was causing the error.

    The "udpSocket.BindEndpointAsync(host, port)" doesn't seem needed.

    I am just doing "udpSocket.ConnectAsync(host, port)", as before + send the request bytes, and the MessageReceived handler gets invoked. I am now using the UI thread dispatcher, and the UDP response propogates via my app-level event.

    Cheers.