Socket 通信有服务器段和客户端
.NET 6.0 C# 10.0
服务器端代码如下:
1 public static void Main(string[] args) 2 { 3 Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 4 IPAddress ipaddress = IPAddress.Parse("127.0.0.1"); 5 IPEndPoint endPoint = new IPEndPoint(ipaddress, 11001); 6 serverSocket.Bind(endPoint); 7 serverSocket.Listen(1); //接收客户端的个数 8 Console.WriteLine($"服务已启动 准备接收数据"); 9 Socket clentSocket = serverSocket.Accept(); //可以接收客户端 10 bool isContinue = true; 11 12 while (isContinue) 13 { 14 byte[] dataBuffer = new byte[1024]; 15 int count = clentSocket.Receive(dataBuffer); 16 17 string msgReceive = Encoding.UTF8.GetString(dataBuffer, 0, count); 18 if (msgReceive == "stop") 19 isContinue = false; 20 Console.WriteLine($"接收到的数据 {msgReceive}"); 21 22 string megSend = msgReceive + "Yes We Du"; 23 byte[] sendData = Encoding.UTF8.GetBytes(megSend); 24 clentSocket.Send(sendData); 25 Console.WriteLine($"发送数据 {sendData}"); 26 } 27 28 Console.WriteLine($"关闭服务 收到关闭信息了"); 29 Console.ReadKey(); 30 clentSocket.Close(); 31 serverSocket.Close(); 32 }
客户端代码如下:
String IP = "127.0.0.1"; int port =8885 ; IPAddress ip = IPAddress.Parse(IP); //将IP地址字符串转换成IPAddress实例 ClientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);//使用指定的地址簇协议、套接字类型和通信协议 IPEndPoint endPoint = new IPEndPoint(ip, port); // 用指定的ip和端口号初始化IPEndPoint实例 ClientSocket.Connect(endPoint); //与远程主机建立连接 Console.WriteLine("开始发送消息"); byte[] message = Encoding.ASCII.GetBytes("Connect the Server"); //通信时实际发送的是字节数组,所以要将发送消息转换字节 ClientSocket.Send(message); Console.WriteLine("发送消息为:" + Encoding.ASCII.GetString(message)); byte[] receive = new byte[1024]; int length = ClientSocket.Receive(receive); // length 接收字节数组长度 Console.WriteLine("接收消息为:" + Encoding.ASCII.GetString(receive)); ClientSocket.Close(); //关闭连接