TCP 通信

TCP 通信


TCP 服务端

Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = new IPAddress(new byte[] { 192, 168, 1, 5 });
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 7788);
tcpServer.Bind(ipEndPoint); // 绑定IP和端口号
tcpServer.Listen(100); // 设置最多有100人连接
Console.WriteLine("开始接客了...");
Socket client = tcpServer.Accept();
Console.WriteLine("一个客户端连接过来了!");

// 接收消息
byte[] data = new byte[1024];
int length = client.Receive(data);
string msg = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine("接收到了客户端的消息:" + msg);

// 发送消息
client.Send(Encoding.UTF8.GetBytes("来了,随便坐"));

client.Close();
tcpServer.Close();

TCP 客户端

Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = new IPAddress(new byte[] { 192, 168, 1, 5 });
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 7788);
tcpClient.Connect(ipEndPoint);
Console.WriteLine("连接上服务器端了!");

// 发送消息
string msg = "我上线了";
tcpClient.Send(Encoding.UTF8.GetBytes(msg));

// 接收消息
byte[] data = new byte[1024];
int length = tcpClient.Receive(data);
Console.WriteLine("收到服务器端的消息:" + Encoding.UTF8.GetString(data, 0, length));

tcpClient.Close();

posted @ 2023-10-04 15:49  天空之城00  阅读(23)  评论(0)    收藏  举报