/// <summary> /// 发送message给user /// </summary> /// <param name="user">指定发给哪个用户</param> /// <param name="message">信息内容</param> private void SendToClient(User user, string message) { try { //将字符串写入网络流,此方法会自动附加字符串长度前缀 user.bw.Write(message); user.bw.Flush(); AddItemToListBox(string.Format("向[{0}]:{1}发送:{2}",user.userName, user.port, message)); } catch { AddItemToListBox(string.Format("向[{0}]发送信息失败",user.userName,user.port)); } }
/// <summary>移除用户</summary> /// <param name="user">指定要删除的用户</param> private void RemoveUser(User user) { userList.Remove(user); user.Close(); AddItemToListBox(string.Format("当前连接用户数:{0}", userList.Count)); }
/// <summary>发送信息给所有客户</summary> /// <param name="user">指定发给哪个用户</param> /// <param name="message">信息内容</param> private void SendToAllClient(User user, string message) { string command = message.Split(',')[0].ToLower(); if (command == "login") { for (int i = 0; i < userList.Count; i++) { SendToClient(userList[i], message); if (userList[i].userName != user.userName) { SendToClient(user, "login," + userList[i].userName +","+ userList[i].port); } } } else if (command == "logout") { for (int i = 0; i < userList.Count; i++) { if (userList[i].userName != user.userName) { SendToClient(userList[i], message); } } } }
/// <summary>接收客户端连接</summary> private void ListenClientConnect() { TcpClient newClient = null; while (true) { try { newClient = myListener.AcceptTcpClient(); } catch { //当单击“停止监听”或者退出此窗体时AcceptTcpClient()会产生异常 //因此可以利用此异常退出循环 break; } //每接受一个客户端连接,就创建一个对应的线程循环接收该客户端发来的信息 User user = new User(newClient); //客户端的端口号 user.port = newClient.Client.RemoteEndPoint.ToString().Split(':')[1]; Thread threadReceive = new Thread(ReceiveData); threadReceive.Start(user); userList.Add(user); AddItemToListBox(string.Format("[{0}]进入", newClient.Client.RemoteEndPoint)); AddItemToListBox(string.Format("当前连接用户数:{0}", userList.Count)); } }