public static HttpStatusCode Decode <T>(Request request, IBufferManager bufferManager, IMessageDecoder decoder, out T result) { result = default(T); var buffer = bufferManager.BorrowBuffer(); int count = request.Body.Read(buffer, 0, buffer.Length); if (count == 0) { bufferManager.ReturnBuffer(buffer); return(HttpStatusCode.BadRequest); } if (count == buffer.Length) { bufferManager.ReturnBuffer(buffer); return(HttpStatusCode.RequestEntityTooLarge); } result = decoder.DecodeMessage <T>(buffer, 0, count); bufferManager.ReturnBuffer(buffer); if (result == null) { return(HttpStatusCode.InternalServerError); } return(HttpStatusCode.OK); }
private async Task Close() { if (Interlocked.Exchange(ref _state, _disposed) == _disposed) { return; } try { if (_keepAliveTracker != null) { _keepAliveTracker.Dispose(); } if (_keepAliveTimeoutTimer != null) { _keepAliveTimeoutTimer.Dispose(); } if (_closingTimeoutTimer != null) { _closingTimeoutTimer.Dispose(); } if (_stream != null) { _stream.Dispose(); _stream = null; } if (_tcpClient != null && _tcpClient.Connected) { _tcpClient.Dispose(); _tcpClient = null; } } catch (Exception) { } if (_receiveBuffer != null) { _bufferManager.ReturnBuffer(_receiveBuffer); } if (_sessionBuffer != null) { _bufferManager.ReturnBuffer(_sessionBuffer); } _log.DebugFormat("Session closed for [{0}] on [{1}] in dispatcher [{2}] with session count [{3}].", this.RemoteEndPoint, DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm:ss.fffffff"), _module.GetType().Name, this.Server.SessionCount - 1); try { await _module.OnSessionClosed(this); } catch (Exception ex) { HandleUserSideError(ex); } }
public byte[] Decompress(byte[] raw, int offset, int count) { var buffer = _bufferAllocator.BorrowBuffer(); try { using (var input = new MemoryStream(raw, offset, count)) using (var deflate = new DeflateStream(input, CompressionMode.Decompress, leaveOpen: true)) using (var memory = new MemoryStream()) { int readCount = 0; do { readCount = deflate.Read(buffer, 0, buffer.Length); if (readCount > 0) { memory.Write(buffer, 0, readCount); } }while (readCount > 0); return(memory.ToArray()); } } finally { _bufferAllocator.ReturnBuffer(buffer); } }
public async Task Close() { if (Interlocked.Exchange(ref _state, _disposed) == _disposed) { return; } try { if (_stream != null) { _stream.Dispose(); _stream = null; } if (_socket != null) { _socket.Dispose(); _socket = null; } } catch (Exception) { } if (_receiveBuffer != null) { _bufferManager.ReturnBuffer(_receiveBuffer); } if (_sessionBuffer != null) { _bufferManager.ReturnBuffer(_sessionBuffer); } _log.DebugFormat("Session closed on [{0}] in dispatcher [{1}] with session count [{2}].", DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm:ss.fffffff"), _dispatcher.GetType().Name, this.Server.SessionCount - 1); try { await _dispatcher.OnSessionClosed(this); } catch (Exception ex) { HandleUserSideError(ex); } }
public async Task Close() { if (Interlocked.Exchange(ref _state, _disposed) == _disposed) { return; } try { if (_stream != null) { _stream.Dispose(); _stream = null; } if (_tcpClient != null && _tcpClient.Connected) { _tcpClient.Dispose(); _tcpClient = null; } } catch (Exception) { } if (_receiveBuffer != null) { _bufferManager.ReturnBuffer(_receiveBuffer); } if (_sessionBuffer != null) { _bufferManager.ReturnBuffer(_sessionBuffer); } _log.DebugFormat("Disconnected from server [{0}] with dispatcher [{1}] on [{2}].", this.RemoteEndPoint, _dispatcher.GetType().Name, DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm:ss.fffffff")); try { await _dispatcher.OnServerDisconnected(this); } catch (Exception ex) { HandleUserSideError(ex); } }
public void Close() { lock (_opsLock) { if (!_closed) { _closed = true; try { if (_stream != null) { _stream.Close(); _stream = null; } if (_tcpClient != null && _tcpClient.Connected) { _tcpClient.Close(); _tcpClient = null; } } catch (Exception ex) { _log.Error(string.Format("Session [{0}] exception occurred, [{1}].", this, ex.Message), ex); } finally { _bufferManager.ReturnBuffer(_receiveBuffer); _bufferManager.ReturnBuffer(_sessionBuffer); } try { _server.RaiseClientDisconnected(this); } catch (Exception ex) { HandleUserSideError(ex); } } } }
private void InternalClose(bool shallNotifyUserSide) { if (Interlocked.Exchange(ref _state, _disposed) == _disposed) { return; } try { if (_keepAliveTracker != null) { _keepAliveTracker.Dispose(); } if (_keepAliveTimeoutTimer != null) { _keepAliveTimeoutTimer.Dispose(); } if (_closingTimeoutTimer != null) { _closingTimeoutTimer.Dispose(); } if (_stream != null) { _stream.Dispose(); _stream = null; } if (_tcpClient != null && _tcpClient.Connected) { _tcpClient.Close(); _tcpClient = null; } } catch (Exception) { } if (_receiveBuffer != null) { _bufferManager.ReturnBuffer(_receiveBuffer); } _receiveBufferOffset = 0; if (shallNotifyUserSide) { _log(string.Format("Disconnected from server [{0}] on [{1}].", this.RemoteEndPoint, DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm:ss.fffffff"))); try { RaiseServerDisconnected(); } catch (Exception ex) { HandleUserSideError(ex); } } }
public static void AppendBuffer(IBufferManager bufferManager, ref byte[] receiveBuffer, int receiveCount, ref byte[] sessionBuffer, ref int sessionBufferCount) { if (sessionBuffer.Length < (sessionBufferCount + receiveCount)) { byte[] autoExpandedBuffer = bufferManager.BorrowBuffer(); if (autoExpandedBuffer.Length < (sessionBufferCount + receiveCount) * 2) { bufferManager.ReturnBuffer(autoExpandedBuffer); autoExpandedBuffer = new byte[(sessionBufferCount + receiveCount) * 2]; } Array.Copy(sessionBuffer, 0, autoExpandedBuffer, 0, sessionBufferCount); var discardBuffer = sessionBuffer; sessionBuffer = autoExpandedBuffer; bufferManager.ReturnBuffer(discardBuffer); } Array.Copy(receiveBuffer, 0, sessionBuffer, sessionBufferCount, receiveCount); sessionBufferCount = sessionBufferCount + receiveCount; }
public void Close() { lock (_opsLock) { if (!_closed) { _closed = true; try { if (_stream != null) { _stream.Dispose(); _stream = null; } if (_tcpClient != null && _tcpClient.Connected) { _tcpClient.Dispose(); _tcpClient = null; } try { RaiseServerDisconnected(); } catch (Exception ex) { HandleUserSideError(ex); } } finally { _bufferManager.ReturnBuffer(_receiveBuffer); _bufferManager.ReturnBuffer(_sessionBuffer); } } } }
public static void ReplaceBuffer(IBufferManager bufferManager, ref byte[] receiveBuffer, ref int receiveBufferOffset, int receiveCount) { if ((receiveBufferOffset + receiveCount) < receiveBuffer.Length) { receiveBufferOffset = receiveBufferOffset + receiveCount; } else { byte[] autoExpandedBuffer = bufferManager.BorrowBuffer(); if (autoExpandedBuffer.Length < (receiveBufferOffset + receiveCount) * 2) { bufferManager.ReturnBuffer(autoExpandedBuffer); autoExpandedBuffer = new byte[(receiveBufferOffset + receiveCount) * 2]; } Array.Copy(receiveBuffer, 0, autoExpandedBuffer, 0, receiveBufferOffset + receiveCount); receiveBufferOffset = receiveBufferOffset + receiveCount; var discardBuffer = receiveBuffer; receiveBuffer = autoExpandedBuffer; bufferManager.ReturnBuffer(discardBuffer); } }
public static void ShiftBuffer(IBufferManager bufferManager, int shiftStart, ref byte[] sessionBuffer, ref int sessionBufferCount) { if ((sessionBufferCount - shiftStart) < shiftStart) { Array.Copy(sessionBuffer, shiftStart, sessionBuffer, 0, sessionBufferCount - shiftStart); sessionBufferCount = sessionBufferCount - shiftStart; } else { byte[] copyBuffer = bufferManager.BorrowBuffer(); if (copyBuffer.Length < (sessionBufferCount - shiftStart)) { bufferManager.ReturnBuffer(copyBuffer); copyBuffer = new byte[sessionBufferCount - shiftStart]; } Array.Copy(sessionBuffer, shiftStart, copyBuffer, 0, sessionBufferCount - shiftStart); Array.Copy(copyBuffer, 0, sessionBuffer, 0, sessionBufferCount - shiftStart); sessionBufferCount = sessionBufferCount - shiftStart; bufferManager.ReturnBuffer(copyBuffer); } }
private void Close(bool shallNotifyUserSide) { lock (_opsLock) { if (!_closed) { _closed = true; try { if (_stream != null) { _stream.Dispose(); _stream = null; } if (_tcpClient != null && _tcpClient.Connected) { _tcpClient.Dispose(); _tcpClient = null; } } finally { _bufferManager.ReturnBuffer(_receiveBuffer); _receiveBufferOffset = 0; } if (shallNotifyUserSide) { try { RaiseServerDisconnected(); } catch (Exception ex) { HandleUserSideError(ex); } } } } }
private async Task Close(bool shallNotifyUserSide) { if (Interlocked.Exchange(ref _state, _disposed) == _disposed) { return; } try { if (_socket != null && _socket.Connected) { _socket.Dispose(); _socket = null; } } catch (Exception) { } if (_receiveBuffer != null) { _bufferManager.ReturnBuffer(_receiveBuffer); } _receiveBufferOffset = 0; if (shallNotifyUserSide) { /*_log.DebugFormat("Disconnected from server [{0}] with dispatcher [{1}] on [{2}].", * this.RemoteEndPoint, * _dispatcher.GetType().Name, * DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm:ss.fffffff"));*/ try { await _dispatcher.OnServerDisconnected(this); } catch (Exception ex) { HandleUserSideError(ex); } } }
/// <summary> /// Asynchronously reads the entire content of the stream and writes it to the given output stream. /// </summary> /// <param name="stream">The origin stream.</param> /// <param name="toStream">The destination stream.</param> /// <param name="bufferManager">IBufferManager instance to use. May be null.</param> /// <param name="copyLength">Number of bytes to copy from source stream to destination stream. Cannot be passed with a value for maxLength.</param> /// <param name="maxLength">Maximum length of the source stream. Cannot be passed with a value for copyLength.</param> /// <param name="calculateMd5">Bool value indicating whether the Md5 should be calculated.</param> /// <param name="executionState">An object that stores state of the operation.</param> /// <param name="streamCopyState">An object that represents the current state for the copy operation.</param> /// <param name="token">A CancellationToken to observe while waiting for the copy to complete.</param> /// <returns>The task object representing the asynchronous operation.</returns> internal static async Task WriteToAsync <T>(this Stream stream, Stream toStream, IBufferManager bufferManager, long?copyLength, long?maxLength, bool calculateMd5, ExecutionState <T> executionState, StreamDescriptor streamCopyState, CancellationToken token) { if (copyLength.HasValue && maxLength.HasValue) { throw new ArgumentException(SR.StreamLengthMismatch); } if (stream.CanSeek && maxLength.HasValue && stream.Length - stream.Position > maxLength) { throw new InvalidOperationException(SR.StreamLengthError); } if (stream.CanSeek && copyLength.HasValue && stream.Length - stream.Position < copyLength) { throw new ArgumentOutOfRangeException("copyLength", SR.StreamLengthShortError); } if (streamCopyState != null && calculateMd5 && streamCopyState.Md5HashRef == null) { streamCopyState.Md5HashRef = new MD5Wrapper(); } CancellationTokenSource cts = null; byte[] buffer = bufferManager != null?bufferManager.TakeBuffer(GetBufferSize(stream)) : new byte[GetBufferSize(stream)]; try { if (executionState.OperationExpiryTime.HasValue) { // Setup token for timeout cts = CancellationTokenSource.CreateLinkedTokenSource(token); cts.CancelAfter(executionState.RemainingTimeout); // Switch tokens token = cts.Token; } long?bytesRemaining = copyLength; int readCount; do { // Determine how many bytes to read this time so that no more than count bytes are read int bytesToRead = bytesRemaining.HasValue && bytesRemaining < buffer.Length ? (int)bytesRemaining : buffer.Length; if (bytesToRead == 0) { break; } readCount = await stream.ReadAsync(buffer, 0, bytesToRead, token).ConfigureAwait(false); if (bytesRemaining.HasValue) { bytesRemaining -= readCount; } if (readCount > 0) { await toStream.WriteAsync(buffer, 0, readCount, token).ConfigureAwait(false); // Update the StreamDescriptor after the bytes are successfully committed to the output stream if (streamCopyState != null) { streamCopyState.Length += readCount; if (maxLength.HasValue && streamCopyState.Length > maxLength.Value) { throw new InvalidOperationException(SR.StreamLengthError); } if (streamCopyState.Md5HashRef != null) { streamCopyState.Md5HashRef.UpdateHash(buffer, 0, readCount); } } } }while (readCount > 0); if (bytesRemaining.HasValue && bytesRemaining != 0) { throw new ArgumentOutOfRangeException("copyLength", SR.StreamLengthShortError); } } finally { if (cts != null) { cts.Dispose(); cts = null; } if (buffer != null && bufferManager != null) { bufferManager.ReturnBuffer(buffer); } } // Streams opened with AsStreamForWrite extension need to be flushed // to write all buffered data to the underlying Windows Runtime stream. await toStream.FlushAsync().ConfigureAwait(false); if (streamCopyState != null && streamCopyState.Md5HashRef != null) { streamCopyState.Md5 = streamCopyState.Md5HashRef.ComputeHash(); streamCopyState.Md5HashRef = null; } }