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(); }
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); }