27

I was looking for the best solution to receive and process messages via UdpClient class in C#. Does anyone have any solutions for this?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Saanch
  • 1,814
  • 1
  • 24
  • 38
  • 4
    What have you tried so far? What do you not like about it/make you believe there is a "better" solution? – dtb Sep 01 '11 at 04:42

2 Answers2

46

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);
}
unloco
  • 6,928
  • 2
  • 47
  • 58
Hossein Mobasher
  • 4,382
  • 5
  • 46
  • 73
  • 25
    +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. – Jim Mischel Sep 14 '11 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 http://stackoverflow.com/questions/32837887/udp-client-server – SANDEEP Oct 01 '15 at 06:28
  • 1
    What is `recv`? – EgoPingvina Dec 07 '16 at 16:27
  • private void recv(IAsyncResult res) – Matteo TeoMan Mangano Apr 29 '19 at 09:58
  • recv is shorthand for receive. – person27 Jun 21 '19 at 02:49
  • recv is the method private void recv(IAsyncResult res) should really have been private void Recv(IAsyncResult ar) but to each their own. – Levon Ravel Jun 22 '19 at 05:10
  • @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. – henon Jan 03 '20 at 12:10
  • The new async and await methods are so much better than the old way described here. – C.J. Aug 18 '20 at 04:26
22

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);
                }
            }
        });
    }
Mehrad
  • 4,093
  • 4
  • 43
  • 61
  • 1
    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? – Slesa Jul 31 '15 at 15:06
  • is there any equivalent for this Task.Run in .net 3.5? – Nyerguds Feb 22 '16 at 13:39
  • 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. – Alexander Jun 09 '17 at 12:00
  • 2
    any idea why .net is missing IPEndPoint from ReceiveAsync method? how would you send a message back to the sender? – scape Dec 09 '20 at 21:29
  • 1
    @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" – Gardes Jan 28 '22 at 06:32