public static void ReceiveMessage(Object SocketClient) { Socket ReceiveSocket = (Socket)SocketClient; while (true) { byte[] result = new byte[1024 * 1024]; try { IPAddress ClientIP = (ReceiveSocket.RemoteEndPoint as IPEndPoint).Address; int ClientPort = (ReceiveSocket.RemoteEndPoint as IPEndPoint).Port; int ReceiveLength = ReceiveSocket.Receive(result); string ReceiveMessage = Encoding.Unicode.GetString(result, 0, ReceiveLength); Console.WriteLine("接收客户端:" + ReceiveSocket.RemoteEndPoint.ToString() + "时间:" + DateTime.Now.ToString() + "\r\n" + "消息:" + ReceiveMessage + "\r\n\n"); foreach (string key in new List <string>(ClientInformation.Keys)) { string s = ReceiveSocket.RemoteEndPoint.ToString(); if (key != s) { Socket socket = ClientInformation[key]; Console.WriteLine("向客户端{0}发送消息:", key); socket.Send(Encoding.Unicode.GetBytes(ReceiveMessage)); } } //Console.WriteLine("向客户端{0}发送消息:", ReceiveSocket.RemoteEndPoint.ToString()); //string sb = Console.ReadLine(); //ReceiveSocket.Send(Encoding.UTF8.GetBytes(sb)); } catch (Exception ex) { Console.WriteLine("监听出现异常!!!"); Console.WriteLine("客户端" + ReceiveSocket.RemoteEndPoint + "已经连接中断" + "\r\n" + ex.Message + "\r\n" + ex.StackTrace + "\r\n"); foreach (string key in new List <string>(ClientInformation.Keys)) { string s = ReceiveSocket.RemoteEndPoint.ToString(); if (key.Equals(s)) { ClientInformation.Remove(key); } } ReceiveSocket.Shutdown(SocketShutdown.Both); ReceiveSocket.Close(); break; } } }