I was looking for the best solution to receive and process messages via UdpClient
class in C#
. Does anyone have any solutions for this?
-
4What have you tried so far? What do you not like about it/make you believe there is a "better" solution?– dtbSep 1, 2011 at 4:42
3 Answers
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);
}
-
24+1: A couple of notes. First, it's probably not a good idea to call
MessageBox.Show
for error handling, especially in an async callback. But I'll assume you just meant that as, "for example." Second, you probably want to issue the nextBeginReceive
immediately after callingEndReceive
-- before processing the item. Otherwise you can miss messages that arrive while you're processing. Of course, then your async callback has to be re-entrant (i.e. thread safe), but then it already should be. Sep 14, 2011 at 23:02 -
is this code work for multiple clients which send request asynchronously.i m stuck in same issue where i have to write the code for multiple client.here my question stackoverflow.com/questions/32837887/udp-client-server– SANDEEPOct 1, 2015 at 6:28
-
1
-
-
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);
}
}
});
}
-
Yes, this probably runs. But consider an environment such as Unity 3D where you do not have multitasking / multithreading. What do you do in this case?– SlesaJul 31, 2015 at 15:06
-
-
3@Slesa Late response but you can use multitasking/multithreading in Unity. You just need to access Unity stuff on main thread, everything else can be done on other threads. Jun 9, 2017 at 12:00
-
1any idea why .net is missing IPEndPoint from ReceiveAsync method? how would you send a message back to the sender?– scapeDec 9, 2020 at 21:29
-
@scape it will be in the result UdpReceiveResult->RemoteEndPoint. in a synchronous method, it is not in vain that the RemoteEndPoint parameter is passed through "ref"– GardesJan 28 at 6:32
I can recommend two links about this solution which were helpful for me.
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)