public void ParseIncomingDataWithInvalidSizeTest()
        {
            _packetParser = new NetPacketParser(_packetProcessor);
            var token = new NetDataToken();

            Assert.Throws <InvalidOperationException>(() => _packetParser.ParseIncomingData(token, _invalidBuffer, 32));
        }
        public void ParseIncomingDataWithHeaderTest(int bytesTransfered)
        {
            _packetParser = new NetPacketParser(new DefaultNetPacketProcessor(includeHeader: true));

            var token = new NetDataToken();
            int numberOfReceivesNeeded = (_buffer.Length / bytesTransfered) + 1;
            var receviedMessages       = new List <byte[]>();

            for (int i = 0; i < numberOfReceivesNeeded; i++)
            {
                byte[] incomingBuffer = _buffer.Skip(i * bytesTransfered).Take(bytesTransfered).ToArray();

                IEnumerable <byte[]> messages = _packetParser.ParseIncomingData(token, incomingBuffer, Math.Min(bytesTransfered, incomingBuffer.Length));

                if (messages.Any())
                {
                    receviedMessages.AddRange(messages);
                }
            }

            Assert.Single(receviedMessages);

            string messageContent = Encoding.UTF8.GetString(_buffer);

            Assert.Equal(messageContent, Encoding.UTF8.GetString(receviedMessages.Single().ToArray()));
        }
Пример #3
0
        private void ProcessReceive(NetToken clientToken, SocketAsyncEventArgs socketAsyncEvent)
        {
            if (socketAsyncEvent == null)
            {
                throw new ArgumentNullException(nameof(socketAsyncEvent), "Cannot receive data from a null socket event.");
            }

            if (socketAsyncEvent.BytesTransferred > 0)
            {
                if (socketAsyncEvent.SocketError == SocketError.Success)
                {
                    IEnumerable <byte[]> messages = _packetParser.ParseIncomingData(clientToken, socketAsyncEvent.Buffer, socketAsyncEvent.BytesTransferred);

                    if (messages.Any())
                    {
                        foreach (byte[] message in messages)
                        {
                            ProcessReceivedMessage(clientToken.Client, message);
                        }
                    }

                    if (clientToken.DataStartOffset >= socketAsyncEvent.BytesTransferred)
                    {
                        clientToken.Reset();
                    }

                    ReceiveData(clientToken.Client, socketAsyncEvent);
                }
                else
                {
                    OnError(clientToken.Client, socketAsyncEvent.SocketError);
                }
            }
            else
            {
                ClearSocketEvent(socketAsyncEvent);
                OnDisconnected(clientToken.Client);
            }
        }