send a json message to a udp server in csharp

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

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

class Program {
    static void Main(string[] args) {
        // Specify the address and port of the UDP server
        string serverAddress = "127.0.0.1";
        int serverPort = 1234;

        // Create a UDP client and connect to the server
        UdpClient udpClient = new UdpClient();
        IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(serverAddress), serverPort);

        // Create a JSON object with some data
        var data = new {
            Name = "John",
            Age = 30,
            Height = 1.82
        };

        // Serialize the JSON object to a string
        string json = JsonSerializer.Serialize(data);

        // Convert the string to a byte array and send it to the server
        byte[] bytes = Encoding.UTF8.GetBytes(json);
        udpClient.Send(bytes, bytes.Length, endPoint);

        // Close the client
        udpClient.Close();
        Console.WriteLine("Message sent to UDP server");
    }
}
1049 chars
36 lines

In this example, we create a UdpClient and connect to the UDP server using the server's IP address and port number. We then create a JSON object representing some message data, and serialize it to a string using JsonSerializer.Serialize(). We convert the string to a byte array using Encoding.UTF8.GetBytes() and send it to the server using UdpClient.Send(). Finally, we close the client and print a message indicating that the message was sent.

related categories

gistlibby LogSnag