Reputation: 680
I have a WPF application that receives data through a UDP socket. Now I need to port it to Universal Windows Platform, but the socket does not receive the incoming data.
private void Init()
{
socket = new Socket(SocketType.Dgram, ProtocolType.Udp);
socket.Bind(new IPEndPoint(IPAddress.Parse("192.168.0.1"), 55156));
socketAsyncArgs = new SocketAsyncEventArgs();
buffer = new byte[4096];
socketAsyncArgs.SetBuffer(buffer, 0, buffer.Length);
socketAsyncArgs.Completed += Receive_Completed;
}
private void Receive()
{
bool isPending = socket.ReceiveAsync(socketAsyncArgs);
if ( ! isPending)
Receive_Completed(socket, socketAsyncArgs);
}
The Receive_Completed
method is never called. The same code works well in a WPF project. I used WireShark to verify the packets are coming. I also tried using Windows.Networking.Sockets.DatagramSocket
with the same result - the socket does not receive any data.
Upvotes: 1
Views: 1967
Reputation: 680
I found the solution. Apparently, you have to specifically enable that the application will be receiving incoming network traffic. The UWP project in Visual Studio contains a file named Package.appxmanifest
. Double click it, select the Capabilities tab and check Internet (Client & Server). More about that at the MSDN - Networking basics.
Upvotes: 1
Reputation: 3998
Don't you have to connect First? I dont about socket.bind but you have to set an IPEndPoint
in socketAsyncArgs.RemoteEndPoint
. And please don't call Receive_Completed!!! its an event it should be triggered automatically.
I tested you code with a server and worked(but in TCP and Stream mode)
private void Init()
{
socket = new Socket(SocketType.Dgram, ProtocolType.Udp);
socketAsyncArgs = new SocketAsyncEventArgs();
socketAsyncArgs.RemoteEndPoint = new IPEndPoint(IPAddress.Parse("192.168.0.1"), 55156);
buffer = new byte[4096];
socketAsyncArgs.SetBuffer(buffer, 0, buffer.Length);
socketAsyncArgs.Completed += Receive_Completed;
}
private void Receive()
{
bool isPending = socket.ConnectAsync(socketAsyncArgs);
if (!isPending)
isPending = socket.ReceiveAsync(socketAsyncArgs);
}
Upvotes: 0