public override IAsyncResult BeginReceive(AsyncCallback requestCallback, Object state) { AsyncReceiveRecordsResult asyncReceiveResult = new AsyncReceiveRecordsResult(requestCallback, state); StartReceive(asyncReceiveResult); return(asyncReceiveResult); }
private void StartReceive(AsyncReceiveRecordsResult asyncReceiveResult) { lock (_receiveLock) { if (_receiving) { // Receive in progress, add to queue if (asyncReceiveResult != null) { _receiveQueue.Add(asyncReceiveResult); } return; } if (asyncReceiveResult == null && _receiveQueue.Count > 0) { // Get first asyncReceiveResult in queue asyncReceiveResult = _receiveQueue[0]; _receiveQueue.Remove(asyncReceiveResult); } if (asyncReceiveResult != null) { // Start reading the header _innerStream.BeginRead(_inputBuffer, 0, 5, new AsyncCallback(ReadCallback), asyncReceiveResult); _receiving = true; } } }
private void ReadCallback(IAsyncResult asyncResult) { AsyncReceiveRecordsResult asyncReadResult = (AsyncReceiveRecordsResult)asyncResult.AsyncState; try { int readBytes = _innerStream.EndRead(asyncResult); if (readBytes == 0) { throw new EndOfStreamException("Connection closed while reading TLS record"); } _inputBufferCount += readBytes; // We require at least 5 bytes of header if (_inputBufferCount < 5) { _innerStream.BeginRead(_inputBuffer, _inputBufferCount, 5 - _inputBufferCount, new AsyncCallback(ReadCallback), asyncReadResult); return; } // We require the fragment bytes int fragmentLength = (_inputBuffer[3] << 8) | _inputBuffer[4]; if (5 + fragmentLength > _inputBuffer.Length) { throw new RecordTooLargeException("Received TLS record fragment size too large"); } else if (_inputBufferCount < 5 + fragmentLength) { _innerStream.BeginRead(_inputBuffer, _inputBufferCount, 5 + fragmentLength - _inputBufferCount, new AsyncCallback(ReadCallback), asyncReadResult); return; } // Construct the TLSRecord returned as result Record record = new Record(_inputBuffer); Buffer.BlockCopy(_inputBuffer, 5, record.Fragment, 0, fragmentLength); _inputBufferCount = 0; // Complete the asynchronous read FinishReceive(true); asyncReadResult.AddRecord(record); asyncReadResult.SetComplete(); } catch (Exception e) { FinishReceive(false); asyncReadResult.SetComplete(e); } }
public override Record[] EndReceive(IAsyncResult asyncResult) { AsyncReceiveRecordsResult asyncReceiveResult = (AsyncReceiveRecordsResult)asyncResult; if (!asyncReceiveResult.IsCompleted) { asyncReceiveResult.AsyncWaitHandle.WaitOne(); } if (asyncReceiveResult.CompletedWithException) { throw asyncReceiveResult.AsyncException; } return(asyncReceiveResult.AsyncResult); }
public override IAsyncResult BeginReceive(AsyncCallback requestCallback, Object state) { AsyncReceiveRecordsResult asyncReceiveResult = new AsyncReceiveRecordsResult(requestCallback, state); StartReceive(asyncReceiveResult); return asyncReceiveResult; }