Sending and receiving UDP packets in .NET

Reixons picture Reixons · Jul 14, 2011 · Viewed 10.8k times · Source

I am trying to test UDP communications on a LAN. I have a small piece of code to and I have tried to run it in 2 computers (one should wait to receive and the other one should send). The strange thing is that computer A sends and B receives properly but if I try A to receive and B to send it does not work. Do you know why could it be?

public void SendBroadcast(int port, string message)
    {
        UdpClient client = new UdpClient();
        byte[] packet = Encoding.ASCII.GetBytes(message);

        try
        {
            client.Send(packet, packet.Length, IPAddress.Broadcast.ToString(), port);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

public void Receive(int port)
    {
        UdpClient client = null;

        try
        {
            client = new UdpClient(port);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        IPEndPoint server = new IPEndPoint(IPAddress.Any, 0);


        while (true) 
        {
            try
            {
                byte[] packet = client.Receive(ref server);
                Console.WriteLine("{0}, {1}", server, Encoding.ASCII.GetString(packet));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

And the calls:

  SendBroadcast(444, "hello"); Receive(444);

If I run 2 instances of the program on the same computer it works properly but creates 3 packages per call.

Thanks in advance.

Answer

Jay picture Jay · Jul 14, 2011

Try using the async methods so that you can keep listening for messages without blocking to send messages.