Receive messages continuously using udpClient
I was looking for the best solution to re开发者_如何学JAVAceive and process messages via UdpClient
class in C#
. Does anyone have any solutions for this?
Try this code :
//Client uses as receive udp client
UdpClient Client = new UdpClient(Port);
try
{
Client.BeginReceive(new AsyncCallback(recv), null);
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
//CallBack
private void recv(IAsyncResult res)
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 8000);
byte[] received = Client.EndReceive(res, ref RemoteIpEndPoint);
//Process codes
MessageBox.Show(Encoding.UTF8.GetString(received));
Client.BeginReceive(new AsyncCallback(recv), null);
}
For newer methods using TAP instead of Begin/End method you can use the following in .Net 4.5
Quite simple!
Asynchronous Method
private static void UDPListener()
{
Task.Run(async () =>
{
using (var udpClient = new UdpClient(11000))
{
string loggingEvent = "";
while (true)
{
//IPEndPoint object will allow us to read datagrams sent from any source.
var receivedResults = await udpClient.ReceiveAsync();
loggingEvent += Encoding.ASCII.GetString(receivedResults.Buffer);
}
}
});
}
Synchronous Method
As appose to the asynchronous
method above, this can be also implemented in synchronous
method in a very similar fashion:
private static void UDPListener()
{
Task.Run(() =>
{
using (var udpClient = new UdpClient(11000))
{
string loggingEvent = "";
while (true)
{
//IPEndPoint object will allow us to read datagrams sent from any source.
var remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
var receivedResults = udpClient.Receive(ref remoteEndPoint);
loggingEvent += Encoding.ASCII.GetString(receivedResults);
}
}
});
}
I can recommend two links about this solution which were helpful for me.
PC Related
Stack Overflow
The first one is really easy solution but be careful at modifying because the continual receiving will work only if some UDP packet is sent as first to the "remote" device. For continual listening add the code line "udp.BeginReceive(new AsyncCallback(UDP_IncomingData), udp_ep);" after each reading of incomming data to enable new receiving of UDP packets.
The second one is nice solution for using the Multicast IP-addresses (239.255.255.255 - 240.0.0.0)
精彩评论