Beispiel #1
0
        public async Task <List <IEnvelope> > ReceiveAsync()
        {
            try
            {
                var reader = new EnvelopeReaderBuffer {
                    Buffer = new byte[4096], Payload = null
                };

                using (var socketStream = new SocketStream(this.TcpClient.Client)) // SocketStream is a class I have created
                {
                    //if (_expectTls == true)
                    //	receivedPackets = await TLSEnvelopeReader.ReceivePackets(reader, socketStream, this.cts.Token);
                    //else

                    List <IEnvelope> receivedPackets = await NOTLSEnvelopeReader.ReceivePackets(reader, socketStream, this.cancellationToken);

                    foreach (var packet in receivedPackets)
                    {
                        this.BytesReceived += (ulong)packet.EncipheredPayload.Length;
                    }

                    return(receivedPackets);
                } // does t his something to the underlying socket...? No! Calls NetworkStream.Dispose which calls stream.Close
            }
            catch (Exception e)
            {
                DisposeAndThrow(e);
                return(default);
        public async Task <List <IEnvelope> > SendRequestAsync(byte[] request)
        {
            var response = new List <IEnvelope>();

            try
            {
                await this._sem.WaitAsync(); // this definitely deadlocks sometimes

                if (!this.IsConnected)
                {
                    return(response);
                }
                this._streamSocket.Send(request);


                var bufferSize = 4096;
                var reader     = new EnvelopeReaderBuffer {
                    Buffer = new byte[bufferSize], Payload = null
                };

                using (var socketStream = new SocketStream(this._streamSocket)) // SocketStream is a class I have created
                {
                    List <IEnvelope> receivedPackets;
                    if (this._expectTls == true)
                    {
                        receivedPackets = await TLSEnvelopeReader.ReceivePackets(reader, socketStream, this._cts.Token);
                    }
                    else
                    {
                        receivedPackets = await NOTLSEnvelopeReader.ReceivePackets(reader, socketStream, this._cts.Token);
                    }
                }
            }
            catch (Exception e)
            {
                await DisconnectAsync();

                throw;
            }
            finally
            {
                this._sem.Release();
            }
            return(response);
        }