示例#1
0
        void InitializeHandler(SocketAsyncEventArgs args)
        {
            if (args.SocketError != SocketError.Success)
            {
                CloseSocket();
                return;
            }

            if (args.BytesTransferred > 0)
            {
                if (_packetBuffer.GetRemainingSpace() > 0)
                {
                    // need to receive the header
                    int readHeaderSize = Math.Min(args.BytesTransferred, _packetBuffer.GetRemainingSpace());
                    _packetBuffer.Write(args.Buffer, 0, readHeaderSize);

                    if (_packetBuffer.GetRemainingSpace() > 0)
                    {
                        // Couldn't receive the whole header this time.
                        AsyncReadWithCallback(InitializeHandler);
                        return;
                    }

                    ByteBuffer buffer      = new ByteBuffer(_packetBuffer.GetData());
                    string     initializer = buffer.ReadString((uint)ClientConnectionInitialize.Length);
                    if (initializer != ClientConnectionInitialize)
                    {
                        CloseSocket();
                        return;
                    }

                    byte terminator = buffer.ReadUInt8();
                    if (terminator != '\n')
                    {
                        CloseSocket();
                        return;
                    }

                    // Initialize the zlib stream
                    _compressionStream = new ZLib.z_stream();

                    // Initialize the deflate algo...
                    var z_res1 = ZLib.deflateInit2(_compressionStream, 1, 8, -15, 8, 0);
                    if (z_res1 != 0)
                    {
                        CloseSocket();
                        Log.outError(LogFilter.Network, "Can't initialize packet compression (zlib: deflateInit2_) Error code: {0}", z_res1);
                        return;
                    }

                    _packetBuffer.Reset();
                    HandleSendAuthSession();
                    AsyncRead();
                    return;
                }
            }

            AsyncReadWithCallback(InitializeHandler);
        }
示例#2
0
        public override void ReadHandler(SocketAsyncEventArgs args)
        {
            if (!IsOpen())
            {
                return;
            }

            int currentReadIndex = 0;

            while (currentReadIndex < args.BytesTransferred)
            {
                if (_headerBuffer.GetRemainingSpace() > 0)
                {
                    // need to receive the header
                    int readHeaderSize = Math.Min(args.BytesTransferred, _headerBuffer.GetRemainingSpace());
                    _headerBuffer.Write(args.Buffer, currentReadIndex, readHeaderSize);
                    currentReadIndex += readHeaderSize;

                    if (_headerBuffer.GetRemainingSpace() > 0)
                    {
                        break; // Couldn't receive the whole header this time.
                    }
                    // We just received nice new header
                    if (!ReadHeader())
                    {
                        CloseSocket();
                        return;
                    }
                }

                // We have full read header, now check the data payload
                if (_packetBuffer.GetRemainingSpace() > 0)
                {
                    // need more data in the payload
                    int readDataSize = Math.Min(args.BytesTransferred, _packetBuffer.GetRemainingSpace());
                    _packetBuffer.Write(args.Buffer, currentReadIndex, readDataSize);
                    currentReadIndex += readDataSize;

                    if (_packetBuffer.GetRemainingSpace() > 0)
                    {
                        break; // Couldn't receive the whole data this time.
                    }
                }

                // just received fresh new payload
                ReadDataHandlerResult result = ReadData();
                _headerBuffer.Reset();
                if (result != ReadDataHandlerResult.Ok)
                {
                    if (result != ReadDataHandlerResult.WaitingForQuery)
                    {
                        CloseSocket();
                    }

                    return;
                }
            }

            AsyncRead();
        }
示例#3
0
    void ThreadFunc()
    {
        Debug.Log("socket thread start");

        do
        {
            // connect
            try
            {
                socket.Connect(m_host, m_port);
            }
            catch
            {
                Debug.Log("socket connect failed");
                break;
            }

            // receive packet
            while (true)
            {
                if (mainThreadCloseSocket)
                {
                    break;
                }

                bool ret = socket.Poll(10, SelectMode.SelectRead);
                if (ret)
                {
                    if (socket.Available == 0)
                    {
                        Debug.Log("server disconnect the socket");
                        break;
                    }
                    else
                    {
                        byte[] receive = new byte[socket.Available];
                        int    len     = socket.Receive(receive);

                        receiveBuffer.Write(receive, len);

                        receiveBuffer.HandleReceive();
                    }
                }

                // send packet
                if (sendBuffer.offset > 0)
                {
                    //Debug.LogError("发送网络包到缓冲区");

                    byte[] buffer = new byte[sendBuffer.offset];

                    sendBuffer.Read(ref buffer, (int)sendBuffer.offset);

                    socket.Send(buffer);
                }
            }
        }while(false);

        Debug.Log("socket thread end");
    }
示例#4
0
        /// <summary>
        /// 把响应数据写入到SocketAsyncEventArgs中
        /// 写入成功返回true,否则返回false,表示没有数据返回到客户端
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public bool Write(SocketAsyncEventArgs e)
        {
            int          token  = ((AsyncUserToken)e.UserToken).Token;
            SocketBuffer buffer = SocketBuffers.GetOrAdd(token, t =>
            {
                return(new SocketBuffer(Config.MsgHandle, new ClientOption {
                    EndPoint = (IPEndPoint)e.AcceptSocket.RemoteEndPoint
                }));
            });

            return(buffer.Write(e));
        }