private void CommandProcess(object obj) { int messageType = 0; CommandProcessModel cpModel = (CommandProcessModel)(obj); Socket socketClient = cpModel.socketClient; string msg = cpModel.msg; string IP = cpModel.IP; try { var msgObj = Utils.DeserializeObject(msg); if (Utils.JsonObjectExistProperty(msgObj, "msgType")) { messageType = int.Parse(Utils.GetJsonObjectValue(msgObj, "msgType").ToString()); } else { return; } } catch { return; } switch (messageType) { case (int)(TCPMessageType.会员客户端注册): CommandProcessHandler.Register(socketClient, msg, SessionPool, IP); break; case (int)(TCPMessageType.推送消息): CommandProcessHandler.Push(socketClient, msg, SessionPool, IP); break; case (int)(TCPMessageType.雷达操作回复): CommandProcessHandler.RadarAnswer(socketClient, msg, SessionPool, IP); break; } }
/// <summary> /// 处理接受的数据 /// </summary> /// <param name="socket"></param> private void Recieve(IAsyncResult socket) { Socket SocketClient = (Socket)socket.AsyncState; string IP = SocketClient.RemoteEndPoint.ToString(); if (SocketClient == null || !SessionPool.ContainsKey(IP)) { return; } try { int length = SocketClient.EndReceive(socket); if (length > 0) { byte[] buffer = SessionPool[IP].buffer; SocketClient.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(Recieve), SocketClient); string msg = Encoding.UTF8.GetString(buffer, 0, length); // websocket建立连接的时候,除了TCP连接的三次握手,websocket协议中客户端与服务器想建立连接需要一次额外的握手动作 SocketClientType socketClientType = SocketClientType.UnknownClient; if (TCPClientHelper.IsClientConnctionRequest(msg, out socketClientType)) { SocketClient.Send(PackageHandShakeData(buffer, length)); SessionPool[IP].SocketClientType = socketClientType; return; } if (TCPClientHelper.IsConnected(SessionPool, IP)) { //if (SessionPool[IP].SocketClientType == SocketClientType.WebClient) //{ //} msg = AnalyzeClientData(buffer, length); if (msg != "") { CommandProcessModel cpModel = new CommandProcessModel(SocketClient, msg, IP); Thread commandProcessThread = new Thread(new ParameterizedThreadStart(CommandProcess)) { IsBackground = true, Name = "在线检查线程" }; commandProcessThread.Start(cpModel); } else { CloseSocketClient(SocketClient, IP); } } } } catch { CloseSocketClient(SocketClient, IP); } }