/// <summary> /// 处理客户端发送的消息,接收成功后加入到msgPool,等待广播 /// </summary> /// <param name="result">Result.</param> private void Recieve(IAsyncResult result) { Socket client = result.AsyncState as Socket; if (client == null || !clientPool.ContainsKey (client)) { return; } try { int length = client.EndReceive (result); byte[] buffer = clientPool [client].buffer; //接收消息 client.BeginReceive (buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback (Recieve), client); string msg = Encoding.UTF8.GetString (buffer, 0, length); if (!clientPool [client].IsHandShaked && msg.Contains ("Sec-WebSocket-Key")) { client.Send (PackageHandShakeData (buffer, length)); clientPool [client].IsHandShaked = true; return; } if (IsCloseSocket(client)) return; msg = AnalyzeClientData (buffer, length); SocketMessage sm = new SocketMessage (); sm.Client = clientPool [client]; sm.Time = DateTime.Now; Regex reg = new Regex (@"{<(.*?)>}"); Match m = reg.Match (msg); if (m.Value != "") { //处理客户端传来的用户名 clientPool [client].NickName = Regex.Replace (m.Value, @"{<(.*?)>}", "$1"); sm.isLoginMessage = true; sm.Message = "login!"; Console.WriteLine ("{0} login @ {1}", client.RemoteEndPoint, DateTime.Now); } else { //处理客户端传来的普通消息 sm.isLoginMessage = false; sm.Message = msg; Console.WriteLine ("{0} @ {1}\r\n {2}", client.RemoteEndPoint, DateTime.Now, sm.Message); } msgPool.Add (sm); isClear = false; } catch { //把客户端标记为关闭,并在clientPool中清除 if(client!=null&&client.Connected) { //关闭Socket之前,首选需要把双方的Socket Shutdown掉 client.Shutdown(SocketShutdown.Both); //Shutdown掉Socket后主线程停止10ms,保证Socket的Shutdown完成 System.Threading.Thread.Sleep(10); //关闭客户端Socket,清理资源 client.Close(); Console.WriteLine ("Client {0} disconnet", clientPool [client].Name); clientPool.Remove (client); } } }
/// <summary> /// 把发送给客户端消息打包处理(拼接上谁什么时候发的什么消息) /// </summary> /// <returns>The data.</returns> /// <param name="message">Message.</param> private byte[] PackageServerData(SocketMessage sm) { StringBuilder msg = new StringBuilder (); if (!sm.isLoginMessage) { //消息是login信息 msg.AppendFormat ("{0} @ {1}:\r\n ", sm.Client.Name, sm.Time.ToShortTimeString ()); msg.Append (sm.Message); } else { //处理普通消息 msg.AppendFormat ("{0} login @ {1}", sm.Client.Name, sm.Time.ToShortTimeString ()); } byte[] content = null; byte[] temp = Encoding.UTF8.GetBytes (msg.ToString ()); if (temp.Length < 126) { content = new byte[temp.Length + 6]; content [0] = 0x81; content [1] = (byte)(temp.Length); //已经加上掩码 // content[1] = (byte)(0x80 + temp.Length); //已经加上掩码 //byte[] masks = new byte[] { 01, 01, 01, 01 }; ////加上掩码 //for (var i = 0; i < temp.Length; i++) //{ // temp[i] = (byte)(temp[i] ^ masks[i % 4]); //} //Array.Copy(masks, 0, content, 2, 4); // Array.Copy(temp, 0, content, 6, temp.Length); Array.Copy (temp, 0, content, 2, temp.Length); } else if (temp.Length < 0xFFFF) { content = new byte[temp.Length + 4]; content [0] = 0x81; content [1] = 126; content[3] = (byte)(temp.Length & 0xFF); content[2] = (byte)(temp.Length >> 8 & 0xFF); Array.Copy (temp, 0, content, 4, temp.Length); } else { // 暂不处理超长内容 } return content; }
private void ManageGoOnLine() { string userName = socketContext.GetJsonValue("userName"); ManageInfo clientInfo = new ManageInfo() { userName = userName, onLineTime = DateTime.Now }; manageInfoPool.Add(curClientSocket, clientInfo); mJsonResult json = new mJsonResult() { success = true, msg = string.Format("上线成功,上线时间:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")), clientPostType = "retManageGoOnLine" }; SocketMessage sm = new SocketMessage() { Message = json.ToJson(), SendToClients = new Dictionary<Socket, ClientInfo>() { { curClientSocket, null } } }; msgPool.Add(sm); }
private void DeviceGoOnLine() { string deviceSN = socketContext.GetJsonValue("DeviceSN"); DeviceInfo clientInfo = new DeviceInfo() { deviceSN=deviceSN, onLineTime=DateTime.Now }; devicePool.Add(curClientSocket,clientInfo); mJsonResult json = new mJsonResult() { success = true, msg=string.Format("上线成功,上线时间:{0}",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")), clientPostType = "retDeviceGoOnLine" }; SocketMessage sm = new SocketMessage() { Message = json.ToJson(), SendToClients=new Dictionary<Socket,ClientInfo>(){{curClientSocket,null}} }; msgPool.Add(sm); //设备上线 推送给所有管理页面 GetOnlineDeviceList(); }
private void GetOnlineManageList() { var manageList = (from item in manageInfoPool select item.Value).ToList(); mJsonResult json = new mJsonResult() { success = true, rows = manageList, clientPostType = "retGetOnlineManageList" }; //推送给所有连接的管理页面 Dictionary<Socket, ClientInfo> sendto = ( from a in manageInfoPool select new KeyValuePair<Socket, ClientInfo>(a.Key, null) ).ToDictionary(key => key.Key, value => value.Value); SocketMessage sm = new SocketMessage() { Message = json.ToJson(), SendToClients = sendto }; msgPool.Add(sm); }