create a udp client on a specific port in csharp

To create a UDP client in C#, you can use the built-in UdpClient class from the System.Net.Sockets namespace. To set the port number, you can pass it as a parameter to the constructor.

Here's an example code snippet:

main.cs
using System;
using System.Net;
using System.Net.Sockets;

class UdpClientExample
{
    static void Main()
    {
        // Specify the local port number to use
        int port = 12345;

        // Create a UdpClient on the specified port
        UdpClient client = new UdpClient(port);

        // Send a test message to a remote server
        string message = "Hello, server!";
        byte[] bytes = System.Text.Encoding.ASCII.GetBytes(message);
        IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 54321);
        client.Send(bytes, bytes.Length, remoteEndPoint);

        // Receive a message from any remote host
        while (true)
        {
            IPEndPoint anyEndPoint = new IPEndPoint(IPAddress.Any, 0);
            byte[] receivedBytes = client.Receive(ref anyEndPoint);
            string receivedMessage = System.Text.Encoding.ASCII.GetString(receivedBytes);
            Console.WriteLine($"Received message from {anyEndPoint}: {receivedMessage}");
        }
    }
}
1017 chars
31 lines

In this example, the UDP client is created on port 12345. It sends a test message to a remote server with IP address 127.0.0.1 and port 54321, and then enters an infinite loop to receive any incoming messages on any port. The Receive method blocks until a message is received. The ref keyword is used to pass the anyEndPoint parameter by reference, so that the endpoint can be updated with the actual endpoint of the remote host that sent the message.

gistlibby LogSnag