//向客户端发送消息 private void SendtoClient(User user, string message) { //匿名方式发送 UdpClient sendUdpClient = new UdpClient(0); byte[] sendBytes = Encoding.Unicode.GetBytes(message); remoteIPEndPoint = user.GetIPEndPoint(); sendUdpClient.Send(sendBytes, sendBytes.Length, remoteIPEndPoint); sendUdpClient.Close(); }
//接收消息 private void ReceiveMessage() { remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0); while (true) { try { if (stopFlag_receiveMessage) { break; } string[] splitsubstring = null; IPEndPoint clientIPEndPoint = null; //关闭receiveUdpClient时下面一行代码会产生异常 byte[] receiveBytes = receiveUdpClient.Receive(ref remoteIPEndPoint); string message = Encoding.Unicode.GetString(receiveBytes, 0, receiveBytes.Length); //显示消息内容 listBox1.Items.Add(string.Format("[服务端接收数据]{0}:{1}", remoteIPEndPoint, message)); //处理消息数据 //服务器接受消息后做处理 string[] splitstring = message.Split(','); //解析用户端地址 if (splitstring[0] != "qunliao") { splitsubstring = splitstring[2].Split(':'); clientIPEndPoint = new IPEndPoint(IPAddress.Parse(splitsubstring[0]), int.Parse(splitsubstring[1])); } switch (splitstring[0]) { //若为登录信息 case "login": User user = new User(splitstring[1], clientIPEndPoint); //往在线的用户列表添加新成员 userList.Add(user); listBox1.Items.Add(string.Format("[服务端接收数据]用户{0}{1}加入", user.GetName(), user.GetIPEndPoint())); string sendString = "Accept," + txbServerPort.Text; //向客户端发送应答消息 SendtoClient(user, sendString); listBox1.Items.Add(string.Format("[服务端接收数据]向{0}{1}发出:[{2}]", user.GetName(), user.GetIPEndPoint(), sendString)); for (int i = 0; i < userList.Count; i++) { if (userList[i].GetName() != user.GetName()) { //给在线的其他用户发送广播消息 //通知有新用户加入 SendtoClient(userList[i], message); } } listBox1.Items.Add(string.Format("[服务端接收数据]广播:[{0}]", message)); break; case "logout": for (int i = 0; i < userList.Count; i++) { if (userList[i].GetName() == splitstring[1]) { userList.RemoveAt(i); //移除用户 listBox1.Items.Add(string.Format("[服务端接收数据]用户{0}({1})退出", userList[i].GetName(), userList[i].GetIPEndPoint())); } for (int j = 0; j < userList.Count; j++) { //广播注销消息 SendtoClient(userList[i], message); } listBox1.Items.Add(string.Format("[服务端接收数据]广播:[{0}]", message)); break; } break; case "qunliao": listBox1.Items.Add("[服务端接收数据]收到群发消息"); for (int j = 0; j < userList.Count; j++) { //广播注销消息 SendtoClient(userList[j], message); } listBox1.Items.Add(string.Format("[服务端接收数据]广播:[{0}]", message)); break; } } catch (Exception) { break; } listBox1.Items.Add(string.Format("[服务端接收数据]serverIPEndPoint={0} 接收消息 ", serverIPEndPoint)); } }