/// <summary> /// 处理接受的数据 /// </summary> /// <param name="socket"></param> private void Recieve(IAsyncResult socket) { Socket SockeClient = (Socket)socket.AsyncState; string IP = SockeClient.RemoteEndPoint.ToString(); if (SockeClient == null || !SessionPool.ContainsKey(IP)) { return; } try { int length = SockeClient.EndReceive(socket); if (length > 0) { byte[] buffer = SessionPool[IP].buffer; SockeClient.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(Recieve), SockeClient); string msg = Encoding.UTF8.GetString(buffer, 0, length); // websocket建立连接的时候,除了TCP连接的三次握手,websocket协议中客户端与服务器想建立连接需要一次额外的握手动作 SocketClientType socketClientType = SocketClientType.UnknownClient; if (TCPClientHelper.IsClientConnctionRequest(msg, out socketClientType)) { SockeClient.Send(PackageHandShakeData(buffer, length)); SessionPool[IP].SocketClientType = socketClientType; return; } if (TCPClientHelper.IsConnected(SessionPool, IP)) { if (SessionPool[IP].SocketClientType == SocketClientType.WebClient) { msg = AnalyzeClientData(buffer, length); } CommandProcess(SockeClient, msg, IP); } } } catch { try { //SockeClient.Disconnect(true); CommandProcessHandler.ExceptionAnswer(SockeClient); } catch { } finally { //SessionPool.Remove(IP); } } }
private void CommandProcess(Socket sockeClient, string msg, string IP) { int messageType = 0; 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(sockeClient, msg, SessionPool, IP); break; case (int)(TCPMessageType.读取机器名): CommandProcessHandler.GetMachineName(msg, SessionPool, IP); break; case (int)(TCPMessageType.读取加密狗): CommandProcessHandler.GetDogId(msg, SessionPool, IP); break; case (int)(TCPMessageType.读取身份证): CommandProcessHandler.GetPeopleCard(msg, SessionPool, IP); break; case (int)(TCPMessageType.读取IC卡): CommandProcessHandler.GetICCard(msg, SessionPool, IP); break; case (int)(TCPMessageType.办理新IC卡): CommandProcessHandler.CreateICCard(msg, SessionPool, IP); break; case (int)(TCPMessageType.退卡): CommandProcessHandler.ExitICCard(msg, SessionPool, IP); break; case (int)(TCPMessageType.打印小票): CommandProcessHandler.Print(msg, SessionPool, IP); break; case (int)(TCPMessageType.出币): CommandProcessHandler.Coin(msg, SessionPool, IP); break; case (int)(TCPMessageType.读取加密狗和机器名): CommandProcessHandler.GetDogIdAndMachineName(msg, SessionPool, IP); break; } }