private void RecieveCallbackHandler(RecieveUserToken outerToken, SocketError socketError, IList <ArraySegment <byte> > buffer) { if (socketError != SocketError.Success) { outerToken.RecieveTaskCompletionSource.SetException(new SocketException((int)socketError)); outerToken.Parent._listener.AcceptAsync(null); return; } switch (outerToken.State) { case RecieveState.HeaderRecieving: //TODO make override for Read method to get IList<ArraySegment<byte>> TcpMessageHeader header = TcpMessageHeader.Read(buffer[0].Array, buffer[0].Offset); this._headerReciever.ReleaseCallbackBuffer(buffer); outerToken.RecievedHeader = header; outerToken.State = RecieveState.BodyRecieving; this._bodyReciever.RecieveAsync(outerToken.Socket, header.Size, outerToken, RecieveCallbackHandler); break; case RecieveState.BodyRecieving: TcpMessage message = TcpMessage.CreateMessage(outerToken.RecievedHeader, buffer, this._bodyBufferManager); outerToken.State = RecieveState.BodyRecieved; outerToken.RecieveTaskCompletionSource.SetResult(message); break; default: throw new ArgumentOutOfRangeException(); } outerToken.Parent._listener.AcceptAsync(null); }
public async Task <TcpMessage> ReadAsync([NotNull] IClientConnectionInfo connectionInfo) { if (connectionInfo == null) { throw new ArgumentNullException("connectionInfo"); } byte[] headerBuffer = ReadBytes(connectionInfo.Stream, TcpMessageHeader.HeaderSize, this._сonfiguration.HeaderReadingTimeout); if (headerBuffer == null) { // no buffer to read return(null); } TcpMessageHeader tcpMessageHeader = TcpMessageHeader.Read(headerBuffer); int maxMessageBodySize = this._сonfiguration.GetMaxMessageBodySize(tcpMessageHeader.Command); if (tcpMessageHeader.Size > maxMessageBodySize) { Debug.WriteLine("Message body size limit exceed. Size: {0}, Limit: {1}", tcpMessageHeader.Size, maxMessageBodySize); return(null); } using (BufferWriteStream stream = new BufferWriteStream(this._bodyBufferManager)) { try { TimeSpan bodyReceivingTimeout = this._сonfiguration.GetMessageRecieveTimeout(tcpMessageHeader.Command); int readBytesCount = connectionInfo.Stream.BufferedCopyTo(stream, tcpMessageHeader.Size, bodyReceivingTimeout); if (readBytesCount != tcpMessageHeader.Size) { Debug.WriteLine("Message body not recieved completely. Recieved: {0}, expected: {1} bytes", readBytesCount, tcpMessageHeader.Size); this._bodyBufferManager.CheckIn(stream.Buffers); return(null); } return(TcpMessage.CreateMessage(tcpMessageHeader, stream.Buffers, this._bodyBufferManager)); } catch (Exception) { this._bodyBufferManager.CheckIn(stream.Buffers); throw; } } }