using System; using System.Net.Sockets; class MyTcpClient { static void Main() { try { // Create a TcpClient TcpClient client = new TcpClient("127.0.0.1", 12345); // Get a stream object for reading and writing NetworkStream stream = client.GetStream(); // Send a message to the server byte[] message = System.Text.Encoding.ASCII.GetBytes("Hello, server!"); stream.Write(message, 0, message.Length); // Receive the server's response byte[] buffer = new byte[1024]; int bytesRead = stream.Read(buffer, 0, buffer.Length); string response = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead); Console.WriteLine("Server response: {0}", response); // Clean up stream.Close(); client.Close(); } catch (Exception e) { Console.WriteLine("Exception: {0}", e); } } }
using System; using System.Net; using System.Net.Sockets; class MyTcpListener { static void Main() { try { // Start a TCP listener listening for incoming connections on port 12345 TcpListener listener = new TcpListener(IPAddress.Any, 12345); listener.Start(); Console.WriteLine("Waiting for a connection..."); // Accept an incoming connection TcpClient client = listener.AcceptTcpClient(); Console.WriteLine("Connection accepted."); // Get a stream object for reading and writing NetworkStream stream = client.GetStream(); // Receive a message from the client byte[] buffer = new byte[1024]; int bytesRead = stream.Read(buffer, 0, buffer.Length); string message = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead); Console.WriteLine("Message received: {0}", message); // Send a response to the client byte[] response = System.Text.Encoding.ASCII.GetBytes("Hello, client!"); stream.Write(response, 0, response.Length); // Clean up stream.Close(); client.Close(); listener.Stop(); } catch (Exception e) { Console.WriteLine("Exception: {0}", e); } } }In this example, a TCP listener is started on the local machine to accept incoming connections on port 12345. When a client connects, a message is received from the client and a response is sent back. The listener is then closed when the communication is complete. Package library: The TcpClient class is included in the System.dll assembly, which is part of the .NET Framework. No external packages are required to use the TcpClient class.