create a tcp server in csharp

To create a TCP server in C#, you can use the TcpListener class in .NET. Here's an example of how to create a simple TCP server:

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

class TCPServer {
    static void Main() {
        TcpListener server = null;
        try {
            // Set the TCP IP address and port
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            int port = 6000;

            // Create a new TCP listener
            server = new TcpListener(ipAddress, port);

            // Start the TCP listener
            server.Start();

            Console.WriteLine("Waiting for clients...");

            // Enter the listening loop
            while (true) {
                // Wait for a client connection
                TcpClient client = server.AcceptTcpClient();

                Console.WriteLine("Client connected.");

                // Get a stream to read and write data
                NetworkStream stream = client.GetStream();

                // Read the incoming message
                byte[] buffer = new byte[1024];
                int bytesRead = stream.Read(buffer, 0, buffer.Length);
                string data = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                Console.WriteLine("Received: {0}", data);

                // Send a response back to the client
                byte[] message = Encoding.ASCII.GetBytes("Hello client!");
                stream.Write(message, 0, message.Length);

                // Clean up the client connection
                client.Close();
            }
        } catch (Exception e) {
            Console.WriteLine("Error: {0}", e);
        } finally {
            // Stop listening for new clients
            server?.Stop();
        }
    }
}
1659 chars
53 lines

This example creates a TCP listener that listens on the IP address 127.0.0.1 (localhost) and port 6000. When a client connects, the server reads a message from the client and sends back a response. The server then closes the connection and waits for the next client to connect.

gistlibby LogSnag