Search code examples
c#udp

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);

Solution

  • 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)
        {
        }
    }