private void StartInfo() { try { if (!ServerSocket.IsBound) { IPHostEntry hostEntry = Dns.GetHostByName(Dns.GetHostName()); IPAddress address = hostEntry.AddressList[0]; ServerEndPoint = new IPEndPoint(address, 1122); ServerSocket.Bind(ServerEndPoint); ServerSocket.Listen(2); ClientSocket = ServerSocket.Accept(); } ReceveData = receveData(); //接收数据 sendMessage(ReceveData); //发送数据 } catch (Exception ex) { log.Write("开启监听失败请检查服务端Ip地址是否匹配:" + ex.Message); } }
/// <summary> /// 接收数据 /// </summary> public string receveData() { string jasonMessage = ""; try { while (true) { Thread.Sleep(1); byte[] clientByte = new byte[1024]; int bytelength = ClientSocket.Receive(clientByte); if (bytelength > 0) { jasonMessage = Encoding.Default.GetString(clientByte); return jasonMessage; } ClientSocket = ServerSocket.Accept(); } } catch (Exception ex) { log.Write("接收数据错误原因:" + ex.Message); return null; } }
// 发送 void sendMessage(string jasonMessage) { //4.转换byte byte[] sendByte = Encoding.Default.GetBytes(BallJason); //5. 发送 ClientSocket.Send(sendByte); ClientSocket.Close(); }
Thread.Sleep(1); 这个地方 用socket.accept()用这个
建议去了解下TcpListener。