这个示例代码包含了一个简单的TCP socket通讯的实现。其中包括一个服务器端和一个客户端,服务器端监听指定端口,接受连接并读取客户端发送的数据,然后向客户端发送响应;客户端连接到服务器端,发送数据并接收服务器端的响应。可以按照需要修改端口号、IP地址和数据内容。
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;class SocketCommunication
{static void Main(string[] args){StartServer();StartClient();}static void StartServer(){IPAddress ipAddress = IPAddress.Parse("127.0.0.1");int port = 8888;TcpListener listener = new TcpListener(ipAddress, port);listener.Start();Console.WriteLine("Server is listening on port " + port);TcpClient client = listener.AcceptTcpClient();NetworkStream stream = client.GetStream();byte[] data = new byte[1024];int bytesRead = stream.Read(data, 0, data.Length);string message = Encoding.ASCII.GetString(data, 0, bytesRead);Console.WriteLine("Server received: " + message);byte[] response = Encoding.ASCII.GetBytes("Hello from server");stream.Write(response, 0, response.Length);client.Close();listener.Stop();}static void StartClient(){string serverIp = "127.0.0.1";int port = 8888;TcpClient client = new TcpClient(serverIp, port);NetworkStream stream = client.GetStream();byte[] data = Encoding.ASCII.GetBytes("Hello from client");stream.Write(data, 0, data.Length);byte[] response = new byte[1024];int bytesRead = stream.Read(response, 0, response.Length);string reply = Encoding.ASCII.GetString(response, 0, bytesRead);Console.WriteLine("Client received: " + reply);client.Close();}
}