start a tcp server and listen for incoming connections. when a connection is found, read all data available and then disconnect the client in csharp

Here is a sample code that sets up a TCP listener in C# and listens for incoming connections. Once a client connects, it reads all data available and disconnects the client.

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

public class TCPServer 
{
    public static void Main() 
    {   
        // Set the IP address and port number
        IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
        int port = 12345;

        // Create the listener socket
        TcpListener listener = new TcpListener(ipAddress, port);
        
        // Start listening
        listener.Start();
        Console.WriteLine("Waiting for connections...");

        // Enter the listening loop
        while (true) 
        {
            // Wait for a client connection
            TcpClient client = listener.AcceptTcpClient();
            Console.WriteLine("Client connected.");

            // Read all data available
            byte[] buffer = new byte[client.Available];
            client.GetStream().Read(buffer, 0, buffer.Length);

            // Convert the data to a string
            string data = Encoding.UTF8.GetString(buffer);

            // Print the received data
            Console.WriteLine("Received data: {0}", data);

            // Disconnect the client
            client.Close();
            Console.WriteLine("Client disconnected.");
        }
    }
}
1224 chars
44 lines

Note that this code only reads the data that is available at the time of the connection. If you need to read more data or if the data is being sent in chunks, you will need to implement a loop to read all data.

gistlibby LogSnag