TcpListener server = new TcpListener(IPAddress.Any, 8080); server.Start(); while (true) { Socket client = server.AcceptSocket(); Console.WriteLine("Client connected from " + client.RemoteEndPoint); // Use the client socket to communicate with the client }
using (TcpListener server = new TcpListener(IPAddress.Any, 8080)) { server.Start(); while (true) { using (Socket client = server.AcceptSocket()) using (NetworkStream stream = new NetworkStream(client)) using (StreamReader reader = new StreamReader(stream)) using (StreamWriter writer = new StreamWriter(stream)) { string request = reader.ReadLine(); Console.WriteLine("Received: " + request); writer.WriteLine("Hello, " + request); } } }This example creates a TcpListener instance on port 8080 and starts listening for incoming connections. It then enters a loop that calls AcceptSocket method to block and wait for incoming connections. When a connection request is received, it creates a NetworkStream object to read data from the client, and a StreamWriter object to write data back to the client. It then reads a line of text from the client, prints it to the console, and writes a response back to the client. Package library: System.Net.Sockets, System.IO