send a json message to a tcp server in csharp

To send a JSON message to a TCP server in C#, you can follow these steps:

  1. Serialize your JSON object into a byte array.
main.cs
using System.Text.Json;

// Let's say we have a JSON object like this:
var jsonObject = new { Name = "John", Age = 30, City = "New York" };

// Serialize it into a byte array
byte[] jsonBytes = JsonSerializer.SerializeToUtf8Bytes(jsonObject);
243 chars
8 lines
  1. Connect to the TCP server and get a NetworkStream object.
main.cs
using System.Net.Sockets;

// Connect to the server
var client = new TcpClient("serverIpAddress", serverPort);

// Get the network stream object
var stream = client.GetStream();
178 chars
8 lines
  1. Write the byte array to the stream.
main.cs
// Write the JSON message to the stream
stream.Write(jsonBytes, 0, jsonBytes.Length);
86 chars
3 lines
  1. Close the connection when you're done sending messages.
main.cs
// Close the connection when done
client.Close();
50 chars
3 lines

Put it all together and you get:

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

public class Program
{
    public static void Main()
    {
        // Serialize the JSON object to a byte array
        var jsonObject = new { Name = "John", Age = 30, City = "New York" };
        byte[] jsonBytes = JsonSerializer.SerializeToUtf8Bytes(jsonObject);

        // Connect to the TCP server
        TcpClient client = new TcpClient("serverIpAddress", serverPort);

        // Get the network stream object
        NetworkStream stream = client.GetStream();

        // Send the JSON message to the server
        stream.Write(jsonBytes, 0, jsonBytes.Length);

        // Close the connection
        client.Close();
    }
}
701 chars
26 lines

Note that in this example we're using System.Text.Json to serialize the JSON object, but you can use any JSON serializer you prefer. Additionally, make sure to replace "serverIpAddress" and "serverPort" with the actual IP address and port number of your TCP server.

related categories

gistlibby LogSnag