I was looking for the best solution to receive and process messages via UdpClient
class in C#
. Does anyone have any solutions for this?
Receive messages continuously using udpClient
What have you tried so far? What do you not like about it/make you believe there is a "better" solution? –
Jackknife
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);
}
+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 next BeginReceive
immediately after calling EndReceive
-- 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. –
Upgrade 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 –
Flashback
What is
recv
? –
Chloral private void recv(IAsyncResult res) –
Theall
recv is shorthand for receive. –
Chiarra
recv is the method private void recv(IAsyncResult res) should really have been private void Recv(IAsyncResult ar) but to each their own. –
Balsam
@JimMischel thank you very much for bringing up the re-entrancy issue. I did receive doubles of the same packet in some cases, sometimes even incomplete packets until I protected my EndReceive callback against re-entrancy. –
Recaption
The new async and await methods are so much better than the old way described here. –
Savate
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? –
Savagery
is there any equivalent for this Task.Run in .net 3.5? –
June
@Savagery 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. –
Vociferant
any idea why .net is missing IPEndPoint from ReceiveAsync method? how would you send a message back to the sender? –
Correct
@Correct 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" –
Dotson
© 2022 - 2024 — McMap. All rights reserved.