send a message to a udp server in csharp

Here is an example of how to send a message to a UDP server in C#:

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

class Program {
    static void Main(string[] args) {
        // Create a UDP socket
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        // Create an endpoint for the server
        IPAddress serverAddress = IPAddress.Parse("192.168.1.100");
        IPEndPoint serverEndpoint = new IPEndPoint(serverAddress, 1234);

        // Create a message to send to the server
        string message = "Hello, server!";
        byte[] buffer = System.Text.Encoding.ASCII.GetBytes(message);

        // Send the message to the server
        int bytesSent = socket.SendTo(buffer, serverEndpoint);

        // Clean up the socket
        socket.Close();

        Console.WriteLine("Sent {0} bytes to server.", bytesSent);
        Console.ReadLine();
    }
}
861 chars
28 lines

In this example, we create a UDP socket and specify the server's IP address and port number in an IPEndPoint. We then create a message to send and convert it to a byte array. Finally, we call SendTo on the socket to send the message to the server.

gistlibby LogSnag