Katherina
Katherina

Reputation: 2223

C# UDP listener un-blocking? or prevent revceiving from being stuck

I've been searching for previous problems like mine here but it seems I can't find the answer I need.

My goal is to prevent my UDP listener from not hanging. I have a UDP listener who waits for messages but if there is nothing to receive it just hangs there.

I have read other threads and they say that I need to set the Blocking to false but I can't find how to set it. Sorry I'm just new to C# and to socket programming.

Here's the part of my listener:

while (true)
{
    try
    {
        byte[] data = listener.Receive(ref groupEP);

        IPEndPoint newuser = new IPEndPoint(groupEP.Address, groupEP.Port);
        string sData =  (System.Text.Encoding.ASCII.GetString(data));

    }
    catch (Exception e)
    {
    }
}

My problem is it just freezes on the following line:

byte[] data = listener.Receive(ref groupEP);

Upvotes: 5

Views: 13704

Answers (4)

Elmorr
Elmorr

Reputation: 1

TestHost.Client.Blocking = false;

You need to access the 'Socket' object, beneath the UdpClient object ('TestHost' in the detailed example below), to get to the 'Blocking' property as shown:

int Port = 9020;    //Any port number you like will do
IPAddress ActiveIPaddress = new IPAddress(new byte[] { 192, 168, 3, 10 }); //Any IPaddress you need will do
IPEndPoint HostEP = new IPEndPoint(ActiveIPaddress, Port);
UdpClient TestHost = new UdpClient(Global.HostEP);
TestHost.Client.Blocking = false;

enter image description here

Upvotes: 0

krolth
krolth

Reputation: 1032

You are using the blocking versions of Receive/Send. Consider using the async versions (ReceiveAsync/BeginReceive) instead.

https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.udpclient?view=netcore-3.1

Upvotes: 0

paggi_stackoverflow
paggi_stackoverflow

Reputation: 31

        UdpClient client = new UdpClient();
        //Some code goes here ...
        client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 2000);

//This is pretty clear and simple.

Upvotes: 3

Jake T.
Jake T.

Reputation: 631

Use the available property on the UDPClient (if this is what you are using) to determine if you have data in the network queue to read.

while (true)
{
    try
    {
        if (listener.Available > 0) // Only read if we have some data 
        {                           // queued in the network buffer. 
            byte[] data = listener.Receive(ref groupEP);

            IPEndPoint newuser = new IPEndPoint(groupEP.Address, groupEP.Port);
            string sData =  (System.Text.Encoding.ASCII.GetString(data));
        }
    }
    catch (Exception e)
    {
    }
}

Upvotes: 9

Related Questions