UDP - Receiving in background
Hi.
It has been a REALLY long time so I would appreciate guidance here.
I am using UDPClient to send and receive data.
I have a simple example working but its lifetime is only for 1 time where I can send data and then receive and that's it.
I want the application to be able to continuously receive data in the background (without blocking but processing any data coming through from a server).
How would I do this? I HATE to use a while(true) approach and NO Thread.Sleep code either.
I welcome any advice here to be able to continuously receive data in the background (and still be able to send data)
Thanks!
Re: UDP - Receiving in background
In my chatting program I've used an infinite loop for retrieving UDP packets and it is on a different thread.
Code:
private void WaitForPockets()
{
for (; ; )
{
try
{
byte[] data = client.Receive(ref receivePoint);
string receivedMessage = System.Text.Encoding.ASCII.GetString(data);
NewMessageEventArgs e = new NewMessageEventArgs(Environment.NewLine + receivedMessage);
//Raise event new message
OnNewMessage(e);
}
catch (Exception exc)
{
Logger.LogException(exc);
this.SetStatusBar("Error receiving message from " + Dns.GetHostEntry(receivePoint.Address.ToString()).HostName);
}
}
}
Code:
try
{
client = new UdpClient(_port);
receivePoint = new IPEndPoint(new IPAddress(0), 0);
Thread readThread = new Thread(new ThreadStart(this.WaitForPockets));
readThread.Start();
}
catch (Exception exc)
{
Logger.LogException(exc);
}