create a tcp server on a specific port in csharp

To create a TCP server on a specific port in C#, you can use the TcpListener class from the System.Net.Sockets namespace.

The following code snippet demonstrates how to create a TCP server on port 8080:

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

class Program
{
    static void Main(string[] args)
    {
        // Set the IP address and port number for the server
        IPAddress ipAddress = IPAddress.Any;
        int port = 8080;

        // Create a TCP listener on the specified IP address and port
        TcpListener listener = new TcpListener(ipAddress, port);
        
        // Start listening for incoming client connections
        listener.Start();

        Console.WriteLine("TCP server started on port " + port);

        while (true)
        {
            // Wait for a client to connect
            TcpClient client = listener.AcceptTcpClient();

            Console.WriteLine("Client connected from " + client.Client.RemoteEndPoint);

            // Handle the client connection in a separate thread
            // (not shown in this example)
        }
    }
}
895 chars
33 lines

In this example, ipAddress is set to IPAddress.Any, which means the server will listen for incoming connections on all available network interfaces. If you want to restrict the server to a specific network interface, you can set ipAddress to the IP address of that interface.

The TcpListener instance is then created with the ipAddress and port parameters. The listener.Start() method is called to begin listening for incoming connections on this endpoint.

The while (true) loop listens for incoming client connections using the listener.AcceptTcpClient() method, which blocks until a client connects. When a client connects, a new TcpClient instance is returned, representing the connected client.

You can then handle the client connection in a separate thread or just run the code sequentially to handle it inline with the loop.

gistlibby LogSnag