The goal of this small project is to create two console programs which ping-pong each other over UDP  every 500ms, in order to demonstrate how to set up basic network connectivity. 

In this example, the server waits for incoming messages, known as datagrams, and responds with an empty message.

The code for the server program:


class PingPongServer
{
    static void Main()
    {
        var client = new UdpClient(new IPEndPoint(IPAddress.Loopback, 30000));
        var childEndPoint = default(IPEndPoint);

        while (true)
        {
            _ = client.Receive(ref childEndPoint);
            Console.WriteLine("Received ping from {0}", childEndPoint);

            Console.WriteLine("Sending pong to {0}", childEndPoint);
            client.Send(Array.Empty<byte>(), 0, childEndPoint);
        }
    }
}

The server is bound to the loopback address (127.0.0.1) on port 30000 in the UdpClient constructor. It will listen for incoming packets on this address and port. The variable childEndPoint will be the address and port of the computer (which in this case is your own) that sent the message.

The server then enters an infinite loop waiting to receive an empty packet from the client.

The code for the client:

class PingPongClient
{
    static void Main()
    {
        var client = new UdpClient();
        var serverEndPoint = new IPEndPoint(IPAddress.Loopback, 30000);
        client.Connect(serverEndPoint);

        IPEndPoint remoteEndPoint = null;   // this will always be equal to serverEndPoint in our example
        while (true)
        {
            Console.WriteLine("Sending ping to server");
            client.Send(Array.Empty<byte>(), 0);

            Thread.Sleep(500);

            _ = client.Receive(ref remoteEndPoint);
            Console.WriteLine("Received pong from server");
        }
    }
}

The client is created using the empty UdpClient constructor which sets the address to the loopback 127.0.0.1 and assigns a port dynamically. We know the server address and port number so we can use the UdpClient.Connect() method to establish a default destination when sending packets - as you can see from client.Send(Array.Empty<byte>(), 0) - no address or port were mentioned as they were inferred from Connect().

The program then enters an infinite loop which starts by sending an empty packet to the server, waiting 500ms, then waiting to receive a response.

There are many issues and limitations with these basic programs, the main one being UDP doesn't guarantee a packet we send will arrive at the server.

Comments


Comments are closed