Пример #1
0
        public async Task SendAsync(byte[] payload, CancellationToken token)
        {
            await Task.Run(async() =>
            {
                var packet = new TcpTransportPacket(_packetNumber++, payload);

                var args = new SocketAsyncEventArgs();
                args.SetBuffer(packet.Data, 0, packet.Data.Length);

                var awaitable = new SocketAwaitable(args);
                await _socket.SendAsync(awaitable);
            }, token).ConfigureAwait(false);
        }
Пример #2
0
        public Task SendAsync(byte[] payload, CancellationToken token)
        {
            ThrowIfDisposed();
            return(Task.Run(async() =>
            {
                var packet = new TcpTransportPacket(_packetNumber++, payload);

                var args = new SocketAsyncEventArgs();
                args.SetBuffer(packet.Data, 0, packet.Data.Length);

                _socket.SendAsync(args);
            }, token));
        }
Пример #3
0
        /// <summary>
        ///     Try load TCP transport packet from a buffer.
        /// </summary>
        /// <param name="buffer">Buffer.</param>
        /// <param name="packet">Packet.</param>
        /// <returns>True - success, False - fail.</returns>
        public static bool TryLoad(ArraySegment <byte> buffer, out TcpTransportPacket packet)
        {
            packet = null;
            try
            {
                packet = new TcpTransportPacket(buffer);
                return(true);
            }
            catch (TransportException e)
            {
                Log.Debug(e);
            }

            return(false);
        }
Пример #4
0
 private async Task ProcessReceivedPacket(TcpTransportPacket packet)
 {
     await Task.Run(() => _in.OnNext(packet.GetPayloadCopy()));
 }
Пример #5
0
        private async Task ProcessReceivedDataAsync(ArraySegment<byte> buffer)
        {
            try
            {
                int bytesRead = 0;
                while (bytesRead < buffer.Count)
                {
                    int startIndex = buffer.Offset + bytesRead;
                    int bytesToRead = buffer.Count - bytesRead;

                    if (_nextPacketBytesCountLeft == 0)
                    {
                        int tempLengthBytesToRead = PacketLengthBytesCount - _tempLengthBufferFill;
                        tempLengthBytesToRead = (bytesToRead < tempLengthBytesToRead) ? bytesToRead : tempLengthBytesToRead;
                        Buffer.BlockCopy(buffer.Array, startIndex, _tempLengthBuffer, _tempLengthBufferFill, tempLengthBytesToRead);

                        _tempLengthBufferFill += tempLengthBytesToRead;
                        if (_tempLengthBufferFill < PacketLengthBytesCount)
                        {
                            break;
                        }

                        startIndex += tempLengthBytesToRead;
                        bytesToRead -= tempLengthBytesToRead;

                        _tempLengthBufferFill = 0;
                        _nextPacketBytesCountLeft = _tempLengthBuffer.ToInt32();

                        if (_nextPacketDataBuffer == null || _nextPacketDataBuffer.Length < _nextPacketBytesCountLeft || _nextPacketStreamer == null)
                        {
                            _nextPacketDataBuffer = new byte[_nextPacketBytesCountLeft];
                            _nextPacketStreamer = new TLStreamer(_nextPacketDataBuffer);
                        }

                        // Writing packet length.
                        _nextPacketStreamer.Write(_tempLengthBuffer);
                        _nextPacketBytesCountLeft -= PacketLengthBytesCount;
                        bytesRead += PacketLengthBytesCount;
                    }

                    bytesToRead = bytesToRead > _nextPacketBytesCountLeft ? _nextPacketBytesCountLeft : bytesToRead;

                    _nextPacketStreamer.Write(buffer.Array, startIndex, bytesToRead);

                    bytesRead += bytesToRead;
                    _nextPacketBytesCountLeft -= bytesToRead;

                    if (_nextPacketBytesCountLeft > 0)
                    {
                        break;
                    }

                    var packet = new TcpTransportPacket(_nextPacketDataBuffer, 0, (int) _nextPacketStreamer.Position);

                    await ProcessReceivedPacket(packet);

                    _nextPacketBytesCountLeft = 0;
                    _nextPacketStreamer.Position = 0;
                }
            }
            catch (Exception)
            {
                if (_nextPacketStreamer != null)
                {
                    _nextPacketStreamer.Dispose();
                    _nextPacketStreamer = null;
                }
                _nextPacketDataBuffer = null;
                _nextPacketBytesCountLeft = 0;

                throw;
            }
        }
Пример #6
0
        public Task SendAsync(byte[] payload, CancellationToken token)
        {
            ThrowIfDisposed();
            return Task.Run(async () =>
            {
                var packet = new TcpTransportPacket(_packetNumber++, payload);

                var args = new SocketAsyncEventArgs();
                args.SetBuffer(packet.Data, 0, packet.Data.Length);

                var awaitable = new SocketAwaitable(args);
                await _socket.SendAsync(awaitable);
            }, token);
        }
Пример #7
0
 private async Task ProcessReceivedPacket(TcpTransportPacket packet)
 {
     await Task.Run(() => _in.OnNext(packet.GetPayloadCopy()));
 }
Пример #8
0
        private async Task ProcessReceivedDataAsync(ArraySegment <byte> buffer)
        {
            try
            {
                int bytesRead = 0;
                while (bytesRead < buffer.Count)
                {
                    int startIndex  = buffer.Offset + bytesRead;
                    int bytesToRead = buffer.Count - bytesRead;

                    if (_nextPacketBytesCountLeft == 0)
                    {
                        int tempLengthBytesToRead = PacketLengthBytesCount - _tempLengthBufferFill;
                        tempLengthBytesToRead = (bytesToRead < tempLengthBytesToRead) ? bytesToRead : tempLengthBytesToRead;
                        Buffer.BlockCopy(buffer.Array, startIndex, _tempLengthBuffer, _tempLengthBufferFill, tempLengthBytesToRead);

                        _tempLengthBufferFill += tempLengthBytesToRead;
                        if (_tempLengthBufferFill < PacketLengthBytesCount)
                        {
                            break;
                        }

                        startIndex  += tempLengthBytesToRead;
                        bytesToRead -= tempLengthBytesToRead;

                        _tempLengthBufferFill     = 0;
                        _nextPacketBytesCountLeft = _tempLengthBuffer.ToInt32();

                        if (_nextPacketDataBuffer == null || _nextPacketDataBuffer.Length < _nextPacketBytesCountLeft || _nextPacketStreamer == null)
                        {
                            _nextPacketDataBuffer = new byte[_nextPacketBytesCountLeft];
                            _nextPacketStreamer   = new TLStreamer(_nextPacketDataBuffer);
                        }

                        // Writing packet length.
                        _nextPacketStreamer.Write(_tempLengthBuffer);
                        _nextPacketBytesCountLeft -= PacketLengthBytesCount;
                        bytesRead += PacketLengthBytesCount;
                    }

                    bytesToRead = bytesToRead > _nextPacketBytesCountLeft ? _nextPacketBytesCountLeft : bytesToRead;

                    _nextPacketStreamer.Write(buffer.Array, startIndex, bytesToRead);

                    bytesRead += bytesToRead;
                    _nextPacketBytesCountLeft -= bytesToRead;

                    if (_nextPacketBytesCountLeft > 0)
                    {
                        break;
                    }

                    var packet = new TcpTransportPacket(_nextPacketDataBuffer, 0, (int)_nextPacketStreamer.Position);

                    await ProcessReceivedPacket(packet);

                    _nextPacketBytesCountLeft    = 0;
                    _nextPacketStreamer.Position = 0;
                }
            }
            catch (Exception)
            {
                if (_nextPacketStreamer != null)
                {
                    _nextPacketStreamer.Dispose();
                    _nextPacketStreamer = null;
                }
                _nextPacketDataBuffer     = null;
                _nextPacketBytesCountLeft = 0;

                throw;
            }
        }
        /// <summary>
        ///     Try load TCP transport packet from a buffer.
        /// </summary>
        /// <param name="buffer">Buffer.</param>
        /// <param name="packet">Packet.</param>
        /// <returns>True - success, False - fail.</returns>
        public static bool TryLoad(ArraySegment<byte> buffer, out TcpTransportPacket packet)
        {
            packet = null;
            try
            {
                packet = new TcpTransportPacket(buffer);
                return true;
            }
            catch (TransportException e)
            {
                Console.WriteLine(e);
            }

            return false;
        }
        public async Task Should_send()
        {
            TcpClientTransport clientTransport = CreateTcpTransport();

            await clientTransport.ConnectAsync();
            
            Socket clientSocket = _serverSocket.Accept();

            byte[] payload = "010203040506070809".HexToBytes();

            await clientTransport.SendAsync(payload);

            var buffer = new byte[30];
            var received = clientSocket.Receive(buffer);

            var packet = new TcpTransportPacket(buffer, 0, received);
            var receivedPayload = packet.GetPayloadCopy();

            receivedPayload.ShouldAllBeEquivalentTo(payload);
        }
        public async Task Should_receive_small_parts_less_than_4_bytes()
        {
            TcpClientTransport clientTransport = CreateTcpTransport();

            Task<byte[]> receiveTask = clientTransport.FirstAsync().Timeout(TimeSpan.FromMilliseconds(3000)).ToTask();

            await clientTransport.ConnectAsync();
            Socket clientSocket = _serverSocket.Accept();

            byte[] payload = "010203040506070809".HexToBytes();

            var packet = new TcpTransportPacket(0x0ABBCCDD, payload);
            byte[] part1 = packet.Data.Take(1).ToArray();
            byte[] part2 = packet.Data.Skip(part1.Length).Take(2).ToArray();
            byte[] part3 = packet.Data.Skip(part1.Length + part2.Length).Take(3).ToArray();
            byte[] part4 = packet.Data.Skip(part1.Length + part2.Length + part3.Length).ToArray();
            
            clientSocket.Send(part1);
            await Task.Delay(100);
            clientSocket.Send(part2);
            await Task.Delay(200);
            clientSocket.Send(part3);
            await Task.Delay(50);
            clientSocket.Send(part4);
            await Task.Delay(50);

            byte[] receivedData = await receiveTask;
            receivedData.Should().Equal(payload);

            await clientTransport.DisconnectAsync();
            clientSocket.Close();
        }
        public async Task Should_receive_multiple_packets()
        {
            TcpClientTransport clientTransport = CreateTcpTransport();

            var receivedMessages = new AsyncProducerConsumerQueue<byte[]>();
            clientTransport.Subscribe(receivedMessages.Enqueue);

            await clientTransport.ConnectAsync();
            Socket clientSocket = _serverSocket.Accept();

            byte[] payload1 = Enumerable.Range(0, 10).Select(i => (byte) i).ToArray();
            var packet1 = new TcpTransportPacket(0, payload1);

            byte[] payload2 = Enumerable.Range(11, 40).Select(i => (byte) i).ToArray();
            var packet2 = new TcpTransportPacket(1, payload2);

            byte[] payload3 = Enumerable.Range(51, 205).Select(i => (byte) i).ToArray();
            var packet3 = new TcpTransportPacket(2, payload3);

            byte[] allData = ArrayUtils.Combine(packet1.Data, packet2.Data, packet3.Data);

            byte[] dataPart1;
            byte[] dataPart2;
            allData.Split(50, out dataPart1, out dataPart2);

            clientSocket.Send(dataPart1);
            await Task.Delay(100);
            
            clientSocket.Send(dataPart2);
            await Task.Delay(100);

            byte[] receivedData1 = await receivedMessages.DequeueAsync(CancellationTokenHelpers.Timeout(1000).Token);
            receivedData1.Should().Equal(payload1);

            byte[] receivedData2 = await receivedMessages.DequeueAsync(CancellationTokenHelpers.Timeout(1000).Token);
            receivedData2.Should().Equal(payload2);

            byte[] receivedData3 = await receivedMessages.DequeueAsync(CancellationTokenHelpers.Timeout(1000).Token);
            receivedData3.Should().Equal(payload3);

            await clientTransport.DisconnectAsync();
            clientSocket.Close();
        }
        public async Task Should_receive_big_payload()
        {
            TcpClientTransport clientTransport = CreateTcpTransport();

            Task<byte[]> receiveTask = clientTransport.FirstAsync().Timeout(TimeSpan.FromMilliseconds(1000)).ToTask();

            await clientTransport.ConnectAsync();
            Socket clientSocket = _serverSocket.Accept();

            byte[] payload = Enumerable.Range(0, 255).Select(i => (byte) i).ToArray();

            var packet = new TcpTransportPacket(0x0FA0B1C2, payload);
            clientSocket.Send(packet.Data);

            byte[] receivedData = await receiveTask;
            receivedData.Should().Equal(payload);

            await clientTransport.DisconnectAsync();
            clientSocket.Close();
        }
        public async Task Should_receive()
        {
            TcpClientTransport clientTransport = CreateTcpTransport();

            Task<byte[]> receiveTask = clientTransport.FirstAsync().Timeout(TimeSpan.FromMilliseconds(1000)).ToTask();

            await clientTransport.ConnectAsync();
            Socket clientSocket = _serverSocket.Accept();

            byte[] payload = "010203040506070809".HexToBytes();

            var packet = new TcpTransportPacket(0x0FA0B1C2, payload);
            clientSocket.Send(packet.Data);

            byte[] receivedData = await receiveTask;
            receivedData.Should().Equal(payload);

            await clientTransport.DisconnectAsync();
            clientSocket.Close();
        }