Exemple #1
0
        public AsyncSocketInvokeElement(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken)
        {
            m_asyncSocketServer = asyncSocketServer;
            m_asyncSocketUserToken = asyncSocketUserToken;

            m_netByteOrder = true;

            m_incomingDataParser = new IncomingDataParser();
            m_outgoingDataAssembler = new OutgoingDataAssembler();

            m_sendAsync = false;

            m_connectDT = DateTime.UtcNow;
            m_activeDT = DateTime.UtcNow;
        }
Exemple #2
0
        public void CloseClientSocket(AsyncSocketUserToken userToken)
        {
            if (userToken.ConnectSocket == null)
                return;
            string socketInfo = string.Format("Local Address: {0} Remote Address: {1}", userToken.ConnectSocket.LocalEndPoint,
                userToken.ConnectSocket.RemoteEndPoint);
            LogService.LogControl.WriteError(string.Format("Client connection disconnected. {0}", socketInfo));
            try
            {
                userToken.ConnectSocket.Shutdown(SocketShutdown.Both);
            }
            catch (Exception E)
            {
                LogService.LogControl.WriteError(string.Format("CloseClientSocket Disconnect client {0} error, message: {1}", socketInfo, E.Message));
            }
            userToken.ConnectSocket.Close();
            userToken.ConnectSocket = null; //释放引用,并清理缓存,包括释放协议对象等资源

            m_maxNumberAcceptedClients.Release();
            m_asyncSocketUserTokenPool.Push(userToken);
            m_asyncSocketUserTokenList.Remove(userToken);
        }
Exemple #3
0
        // public virtual bool ProcessReceive(byte[] buffer, int offset, int count)
        /// <summary>
        /// 接收异步事件返回的数据,用于对数据进行缓存和分包  modified by zhangyang  20140724
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="offset"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public virtual bool ProcessReceive(AsyncSocketUserToken userToken, int offset, int count)
        {
            m_activeDT = DateTime.UtcNow;

            //拼接数据
            DynamicBufferManager receiveBuffer = m_asyncSocketUserToken.ReceiveBuffer;

            // 写入缓存
            receiveBuffer.WriteBuffer(userToken.ReceiveEventArgs.Buffer, 0, count);
            userToken.DataReceived += count; //增加已读
            bool result = true;

            // 解析包数据 开始符 功能码 包体长度 包体(JSON) 校验码

            //处理数据  // 丢掉脏数据
            userToken.DataReceived = receiveBuffer.DataCount;

            while (receiveBuffer.DataCount > 6) // 长于包头 FF 0a
            {
                while ((receiveBuffer.DataCount > 0) && (receiveBuffer.Buffer[0] != ProtocolConst.StartCharacter))
                {
                    receiveBuffer.Clear(1);
                }
                //按照长度分包
                int packetLength = BitConverter.ToInt32(receiveBuffer.Buffer, 2); //获取包长度
                if (NetByteOrder)
                    packetLength = System.Net.IPAddress.NetworkToHostOrder(packetLength); //把网络字节顺序转为本地字节顺序

                if ((packetLength > 10 * 1024 * 1024) | (receiveBuffer.DataCount > 10 * 1024 * 1024)) //最大Buffer异常保护
                {
                    userToken.DataReceived = 0;
                    return false;
                }
                if ((receiveBuffer.DataCount - 6 - 2) >= packetLength) //收到的数据达到包长度
                {

                    result = ProcessPacket(userToken, receiveBuffer.Buffer, 0, packetLength); //处理分出来的包
                    if (result)
                    {
                        receiveBuffer.Clear(packetLength + 6 + 2); //从缓存中清理
                        userToken.DataReceived -= packetLength + 6 + 2;
                    }
                    else
                        return result;
                }
                else
                {
                    return true;
                }
            }
            return true;
        }
Exemple #4
0
        /// <summary>
        /// 处理分完包后的数据
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="offset"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public virtual bool ProcessPacket(AsyncSocketUserToken userToken, byte[] buffer, int offset, int count)
        {
            //zhangyang  解析包 生成实体
            byte[] tmpbuffer = new byte[count + 6 + 2];
            try
            {

                Array.Copy(buffer, offset, tmpbuffer, 0, count + 8);
                if (tmpbuffer[0] != ProtocolConst.StartCharacter)
                {
                    //标识该包错误 丢弃并关闭连接
                    return false; //
                }
                Byte iFlag = tmpbuffer[1];//功能包
                switch (iFlag)
                {
                    case (byte)ProtocolFlag.Customer:
                        {
                            break;
                        };
                    case (byte)ProtocolFlag.Driver:
                        {
                            break;
                        }

                }
                // 校验数据的准确性
            #if DEBUG
                LogService.LogControl.WriteError(string.Format(" ReceiveData : %s ", BitConverter.ToString(tmpbuffer)));
            #endif
                SendData(userToken.ConnectSocket, tmpbuffer);

                return true;
            }
            catch (Exception ex)
            {
                // 报错记录日志并关闭连接
                LogService.LogControl.WriteError(string.Format("Error Occured in package[ %s  ] because of  : % s ", BitConverter.ToString(tmpbuffer), ex.Message));
                return false;

            }
        }
Exemple #5
0
        public bool DoSendResult(AsyncSocketUserToken token)
        {
            string commandText = m_outgoingDataAssembler.GetProtocolText();
            byte[] bufferUTF8 = Encoding.UTF8.GetBytes(commandText);
            int totalLength = sizeof(int) + bufferUTF8.Length; //获取总大小
            AsyncSendBufferManager asyncSendBufferManager = token.SendBuffer;
            asyncSendBufferManager.StartPacket();
            asyncSendBufferManager.DynamicBufferManager.WriteInt(totalLength, false); //写入总大小
            asyncSendBufferManager.DynamicBufferManager.WriteInt(bufferUTF8.Length, false); //写入命令大小
            asyncSendBufferManager.DynamicBufferManager.WriteBuffer(bufferUTF8); //写入命令内容
            asyncSendBufferManager.EndPacket();

            bool result = true;
            if (!m_sendAsync)
            {
                int packetOffset = 0;
                int packetCount = 0;
                if (asyncSendBufferManager.GetFirstPacket(ref packetOffset, ref packetCount))
                {
                    m_sendAsync = true;
                    result = m_asyncSocketServer.SendAsyncEvent(token.ConnectSocket, token.SendEventArgs,
                        asyncSendBufferManager.DynamicBufferManager.Buffer, packetOffset, packetCount);
                }
            }
            return result;
        }
Exemple #6
0
 public void Init()
 {
     AsyncSocketUserToken userToken;
     //按照连接数建立读写对象
     for (int i = 0; i < m_numConnections; i++)
     {
         userToken = new AsyncSocketUserToken(m_receiveBufferSize);
         userToken.ReceiveEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
         userToken.SendEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
         m_asyncSocketUserTokenPool.Push(userToken);
     }
 }
Exemple #7
0
 private void BuildingSocketInvokeElement(AsyncSocketUserToken userToken)
 {
     /*
      *  modified by zhangyang  20140724
      byte caStart = userToken.ReceiveEventArgs.Buffer[0];
      byte flag = userToken.ReceiveEventArgs.Buffer[userToken.ReceiveEventArgs.Offset];
      if (flag == (byte)ProtocolFlag.Driver)
          userToken.AsyncSocketInvokeElement = new DriverSocketProtocol (this, userToken);
      if (flag == (byte)ProtocolFlag.Customer)
          userToken.AsyncSocketInvokeElement = new ClientSocketProtocol(this, userToken);
      if (userToken.AsyncSocketInvokeElement != null)
      {
          LogService.LogControl.WriteError(string.Format("Building socket invoke element {0}.Local Address: {1}, Remote Address: {2}",
              userToken.AsyncSocketInvokeElement, userToken.ConnectSocket.LocalEndPoint, userToken.ConnectSocket.RemoteEndPoint));
      }
      * */
 }