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);
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
C is an imperative procedural language supporting structured programming, lexical variable scope, and recursion, with a static type system. It was designed to be compiled to provide low-level access to memory and language constructs that map efficiently to machine instructions, all with minimal runtime support.
Full form of C is “COMPILE”. One thing which was missing in C language was further added to C++ that is 'the concept of CLASSES'.
C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.
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)
{
}
}
UdpClient client = new UdpClient();
//Some code goes here ...
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 2000);
//This is pretty clear and simple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With