Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ending a thread safely when using UDP Receive

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();
like image 534
Dumpen Avatar asked Feb 03 '12 01:02

Dumpen


2 Answers

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

like image 115
M.Babcock Avatar answered Sep 30 '22 01:09

M.Babcock


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.

like image 28
Al Kepp Avatar answered Sep 29 '22 23:09

Al Kepp