Safe stream termination when using UDP reception

I create a thread that starts the UDP client that receives the message, after it receives the message that I want to close with the UDP client, and then end the stream, but I don’t know how to end the stream since "Receive", always works until it gets an answer.

This is my code:

private void RecieveChallenge() { UdpClient client = new UdpClient(26000); IPEndPoint remoteIp = new IPEndPoint(IPAddress.Any, 0); Byte[] receivedBytes = client.Receive(ref remoteIp); string ipAddress = Encoding.ASCII.GetString(receivedBytes); } 

The important line is client.Receive (ref remoteIp);

This is how I start my stream:

 Thread recieveChallengeThread = new Thread(new ThreadStart(RecieveChallenge)); recieveDataThread.Start(); 
+4
source share
3 answers

client.Receive will return an empty byte[] when the connection is closed. You just need to close the connection and change the provided code:

 private void RecieveChallenge() { UdpClient client = new UdpClient(26000); IPEndPoint remoteIp = new IPEndPoint(IPAddress.Any, 0); Byte[] receivedBytes = client.Receive(ref remoteIp); if (receivedBytes == null || receivedBytes.Length == 0) return; string ipAddress = Encoding.ASCII.GetString(receivedBytes); } 

Although you probably want a RecieveChallenge to return a boolean value indicating whether it is closed or not (of course, ignoring the fact that your thread will receive only one message).

+6
source

Instead of Receive() you can use BeginReceive() / EndReceive() - this is an asynchronous alternative.

See MSDN: http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.beginreceive.aspx

These methods use the generic .NET APM (Asynchronous Programming Model).

+2
source

If you want to wait for it to complete before continuing with the current thread, you can use

 recieveDataThread.Join(); 

Otherwise, the thread closes as soon as the last line ends.

If you want to finish it earlier, you can use

 recieveDataThread.Abort(); 

from another thread.

+2
source

Source: https://habr.com/ru/post/1394523/


All Articles