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.Receivewill return an emptybyte[]when the connection is closed. You should just have to close the connection and change the provided code to:Though you’ll probably want
RecieveChallengeto return a boolean indicating whether it is closed or not (of course ignoring the fact that your thread will only ever receive one message).