send a message to a tcp server in csharp

To send a message to a TCP server using C#, you can use the TcpClient class provided in the System.Net.Sockets namespace.

Here's an example code snippet that shows how you can use TcpClient to send a message to a TCP server:

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

class Program
{
    static void Main(string[] args)
    {
        try
        {
            // Create a new TCP client
            TcpClient client = new TcpClient();

            // Connect to the server
            client.Connect("localhost", 1234);

            // Get a stream object for writing data to the server
            NetworkStream stream = client.GetStream();

            // Convert the message string to a byte array
            byte[] message = Encoding.ASCII.GetBytes("Hello, server!");

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

            // Close the connection
            client.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: {0}", e);
        }
    }
}
867 chars
36 lines

In this example, we create a new TcpClient object and connect to a server on localhost port 1234. We then get a NetworkStream object for writing data to the server. We convert the message string "Hello, server!" to a byte array, and use the Write method of the NetworkStream object to send the message to the server. Finally, we close the connection.

Note that the Encoding.ASCII.GetBytes method is used to convert the message string to a byte array. This ensures that the message is in a format that can be transmitted over the network.

gistlibby LogSnag