I'm creating a thread that runs a UDP Client that receives a message, after it receives the message I want to close the UDP client and then end the thread, but I dont know how to end the thread since "Receive" always runs until it gets an answer.
This is my code so far:
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);
Here is how I start my thread:
Thread recieveChallengeThread = new Thread(new ThreadStart(RecieveChallenge));
recieveDataThread.Start();
client.Receive
will return an empty byte[]
when the connection is closed. You should just have to close the connection and change the provided code to:
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);
}
Though you'll probably want RecieveChallenge
to return a boolean indicating whether it is closed or not (of course ignoring the fact that your thread will only ever receive one message).
Instead of Receive()
, you can use BeginReceive()
/EndReceive()
- it is an asynchronous alternative.
See MSDN: http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.beginreceive.aspx
These methods use a common APM (asynchronous programming model) of .NET.
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