Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receive messages continuously using udpClient

Tags:

c#

udpclient

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

like image 789
Saanch Avatar asked Sep 01 '11 04:09

Saanch


2 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);
}
like image 60
Hossein Mobasher Avatar answered Oct 29 '22 16:10

Hossein Mobasher


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);
                }
            }
        });
    }
like image 43
Mehrad Avatar answered Oct 29 '22 16:10

Mehrad