- 服务端这里对客户端连接做了try...catch处理,但是无法有效地除掉已经掉线的客户端
- private void button2_Click(object sender, EventArgs e)
- {
- button2.Enabled = false;
- byte[] btMsg = System.Text.Encoding.UTF8.GetBytes("OpenDoor");
- if (dict.Count < 1)
- {
- PlaySoundNobody();
- return;
- }
- //遍历所有的客户端,给每个客户端发送客人到访消息
- foreach (Socket sock in dict.Values)
- {
- try
- {
- sock.Send(btMsg);
- }
- catch (SocketException ex)
- {
- dict.Remove(sock.LocalEndPoint.ToString());
- lbContent.Items.Add(ex.Message);
- }
- }
- //用独立的线程播放音频文件
- Thread thread = new Thread(PlaySound);
- thread.IsBackground = true;
- thread.Start();
- }
复制代码 |