private void ClientAdd(ServerInfo _info) { ClientList.Add(_info); DgAddClient(_info.ClientName + " " + _info.Ip.ToString()); }
/// <summary> /// 监听客户端请求 /// </summary> private void ListenClientConnect() { TcpClient newClient = null; while (true) { ListenClientDelegate d = new ListenClientDelegate(ListenClient); IAsyncResult result = d.BeginInvoke(out newClient, null, null); //使用轮询方式来判断异步操作是否完成 while (result.IsCompleted == false) { if (isExit) break; Thread.Sleep(100); } //获取Begin 方法的返回值和所有输入/输出参数 d.EndInvoke(out newClient, result); if (newClient != null) { //每接受一个客户端连接,就创建一个对应的线程循环接收该客户端发来的信息 ServerInfo info = new ServerInfo(newClient); Thread threadReceive = new Thread(ReceiveData){IsBackground = true}; threadReceive.Start(info); dgAddClient(info); dgLog(string.Format("[{0}]已连接", newClient.Client.RemoteEndPoint)); //dgLog(string.Format("当前连接客户端数:{0}", InfoList.Count)); } else { break; } } }
/// <summary> /// 接收客户端发来的信息 /// </summary> /// <param name="info"></param> /// <param name="receiveMessage"></param> private void ReceiveMessage(ServerInfo info, out string receiveMessage) { try { receiveMessage = info.br.ReadString(); info.Content = Derializer(receiveMessage); } catch (Exception ex) { //AddItemToListBox(ex.Message); receiveMessage = null; } }
/// <summary> /// 发送message给user /// </summary> /// <param name="user"></param> /// <param name="message"></param> private void SendToClient(ServerInfo user) { try { //将字符串写入网络流,此方法会自动附加字符串长度前缀 user.bw.Write(JsonConvert.SerializeObject(user.Content)); user.bw.Flush(); dgLog(string.Format("向[{0}]发送:{1}", user.Content.ClientName, "2&" + (int)user.Content.Order + "&" + user.Content.DataInfo)); } catch { dgLog(string.Format("向[{0}]发送信息失败", user.Content.AimName)); } }
/// <summary> /// 异步发送message给user /// </summary> /// <param name="user"></param> /// <param name="message"></param> private void AsyncSendToClient(ServerInfo info) { foreach (ServerInfo target in InfoList) { if (target.Content.ClientName == info.Content.AimName) { SendToClientDelegate d = new SendToClientDelegate(SendToClient); //ServerInfo s=new ServerInfo(target.client); //s.Content = info.Content; target.Content.DataInfo = info.Content.DataInfo; target.Content.Order = info.Content.Order; IAsyncResult result = d.BeginInvoke(target, null, null); while (result.IsCompleted == false) { if (isExit) break; Thread.Sleep(100); } d.EndInvoke(result); break; } } }
/// <summary> /// 异步发送信息给所有客户 /// </summary> /// <param name="info"></param> /// <param name="message"></param> private void AsyncSendToAllClient(ServerInfo info) { if (info==null) { return; } foreach (var serverInfo in InfoList) { serverInfo.Content.Order = info.Content.Order; serverInfo.Content.DataInfo = info.Content.DataInfo; AsyncSendToClient(serverInfo); } }