Ejemplo n.º 1
0
        public void DataReceived_FullMessage_ReturnsCorrectMessage()
        {
            MessageType expectedMessageType = MessageType.Init;

            byte[] expectedBytes = new byte[] { 1, 2, 3, 4 };

            byte[] message = PacketProtocol <MessageType> .WrapMessage(expectedMessageType, expectedBytes);

            MessageType receivedMessageType = MessageType.Unknown;

            byte[] receivedBytes = null;

            PacketProtocol <MessageType> packetProtocol = new PacketProtocol <MessageType>(100);

            packetProtocol.MessageArrived += (type, bytes) =>
            {
                receivedMessageType = type;
                receivedBytes       = bytes;
            };

            packetProtocol.DataReceived(message, message.Length);

            Assert.AreEqual(expectedMessageType, receivedMessageType);
            Assert.AreEqual(expectedBytes, receivedBytes);
        }
Ejemplo n.º 2
0
        public void Send_message_SendsMessage()
        {
            // Establish the local endpoint for the socket.
            IPHostEntry ipHostInfo    = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress   ipAddress     = ipHostInfo.AddressList[0];
            IPEndPoint  localEndPoint = new IPEndPoint(ipAddress, 20055);

            // Create a server
            Socket server = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            server.Bind(localEndPoint);
            server.Listen(2);

            // Create a SocketConnectionController
            SocketConnection socket = new SocketConnection(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            socket.Connect(localEndPoint);

            SocketConnectionController <MessageType> socketConnectionController = new SocketConnectionController <MessageType>(socket, 1024);

            socketConnectionController.Start();

            Socket server_receiver = server.Accept();

            Thread.Sleep(1000);
            byte[] message      = Encoding.ASCII.GetBytes("ThisIsAMessage");
            byte[] expectedData = PacketProtocol <MessageType> .WrapMessage(MessageType.Standard, message);

            socketConnectionController.Send(MessageType.Standard, message);
            byte[] receiveBuffer = new byte[expectedData.Length];
            server_receiver.Receive(receiveBuffer);
            Assert.AreEqual(expectedData, receiveBuffer);
        }
Ejemplo n.º 3
0
        public void Send_Message_CallsBeginSend()
        {
            MessageType messageType = MessageType.Init;

            byte[] message = Encoding.ASCII.GetBytes("test message");
            var    mock    = new Mock <ISocketConnection>();

            mock.Setup(x => x.Connected).Returns(true);

            byte[] expectedMessage = PacketProtocol <MessageType> .WrapMessage(messageType, message);

            byte[] receivedMessage = null;
            mock.Setup(x => x.BeginSend(
                           It.IsAny <byte[]>(),
                           It.IsAny <int>(),
                           It.IsAny <int>(),
                           It.IsAny <SocketFlags>(),
                           It.IsAny <AsyncCallback>(),
                           It.IsAny <object>()))
            .Callback <byte[], int, int, SocketFlags, AsyncCallback, object>((data, offset, size, socketFlags, asyncCallback, state) =>
            {
                receivedMessage = data;
            });

            SocketConnectionController <MessageType> controller = new SocketConnectionController <MessageType>(mock.Object, 1024);

            controller.Start();
            controller.Send(messageType, message);
            Assert.AreEqual(expectedMessage, receivedMessage);
        }
Ejemplo n.º 4
0
        public void DataReceived_LengthShorterThanBuffer_OnlyReadsTheLength()
        {
            MessageType expectedMessageType = MessageType.Init;

            byte[] expectedBytes = new byte[] { 1, 2, 3, 4 };

            byte[] message = PacketProtocol <MessageType> .WrapMessage(expectedMessageType, expectedBytes);

            // Add bytes the package protocol should not read.
            byte[] tooLongMessage = message.Concat(new byte[] { 9, 8, 7 }).ToArray();

            MessageType receivedMessageType = MessageType.Unknown;

            byte[] receivedBytes = null;

            PacketProtocol <MessageType> packetProtocol = new PacketProtocol <MessageType>(100);

            packetProtocol.MessageArrived += (type, bytes) =>
            {
                receivedMessageType = type;
                receivedBytes       = bytes;
            };

            packetProtocol.DataReceived(tooLongMessage, message.Length);
            Assert.AreEqual(expectedMessageType, receivedMessageType);
            Assert.AreEqual(expectedBytes, receivedBytes);
        }
        // -------------------- SEND -------------------- \\
        public void Send(TMessageType messageType, byte[] message)
        {
            if (!IsConnected)
            {
                throw new Exception("SocketConnectionController is not connected");
            }
            if (_isDisposed)
            {
                throw new ObjectDisposedException("SocketConnectionController has been disposed");
            }

            byte[] data = PacketProtocol <TMessageType> .WrapMessage(messageType, message);

            // Log the incoming message. Ignoring often occurring types.

            /*if (messageType != MessageType.Animation_Request)
             * {
             *  Console.WriteLine($"[OUT] [{messageType}] length:{message.Length}");
             * }*/

            // Begin sending the data to the remote device.
            try
            {
                _socket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), _socket);
            }
            catch (SocketException e)
            {
                OnDisconnect(e);
            }
        }
Ejemplo n.º 6
0
 public async void SendAsync(object data)
 {
     try
     {
         var bytes = PacketProtocol.WrapMessage(netSettings.serializer.Invoke(data));
         await stream.WriteAsync(bytes, 0, bytes.Length);
     }
     catch (Exception ex)
     {
         OnDisconnected?.Invoke(null, new DisconnectEventArgs {
             Exception = ex
         });
     }
 }
Ejemplo n.º 7
0
        public void DataReceived_PackageTooLong_ThrowsProtocolViolationException()
        {
            MessageType expectedMessageType = MessageType.Init;

            byte[] expectedBytes = new byte[] { 1, 2, 3, 4 };

            byte[] message = PacketProtocol <MessageType> .WrapMessage(expectedMessageType, expectedBytes);

            // Add bytes the package protocol should not read.

            PacketProtocol <MessageType> packetProtocol = new PacketProtocol <MessageType>(10);

            Assert.Throws <ProtocolViolationException>(() => packetProtocol.DataReceived(message, message.Length));
        }
Ejemplo n.º 8
0
        public void ReceiveCallback_Message_InvokesMessageArrived()
        {
            // The receive callback is private. We have to chain the receive via the start function.
            MessageType messageType = MessageType.Init;

            byte[] message = Encoding.ASCII.GetBytes("test message");
            var    mock    = new Mock <ISocketConnection>();

            mock.Setup(x => x.Connected).Returns(true);

            byte[] dataToSend = PacketProtocol <MessageType> .WrapMessage(messageType, message);


            var asyncStateMock = new Mock <IAsyncResult>();

            asyncStateMock.Setup(x => x.AsyncState).Returns(dataToSend);

            bool beginReceiveHasBeenInvoked = false;

            mock.Setup(x => x.BeginReceive(
                           It.IsAny <byte[]>(),
                           It.IsAny <int>(),
                           It.IsAny <int>(),
                           It.IsAny <SocketFlags>(),
                           It.IsAny <AsyncCallback>(),
                           It.IsAny <object>()))
            .Callback <byte[], int, int, SocketFlags, AsyncCallback, object>((data, offset, size, socketFlags, asyncCallback, state) =>
            {
                if (!beginReceiveHasBeenInvoked)
                {
                    beginReceiveHasBeenInvoked = true;           // Prevent endless loop
                    asyncCallback.Invoke(asyncStateMock.Object); // calls ReceiveCallBack
                }
            });

            bool endSendCalled = false;

            mock.Setup(x => x.EndReceive(It.IsAny <IAsyncResult>())).Returns(dataToSend.Length).Callback(() => endSendCalled = true);

            SocketConnectionController <MessageType> controller = new SocketConnectionController <MessageType>(mock.Object, 1024);
            MessageReceivedEventArgs <MessageType>   messageReceivedEventArgs = null;

            controller.MessageReceived += (sender, args) => { messageReceivedEventArgs = args; };
            controller.Start();
            Assert.IsTrue(endSendCalled);
            Assert.AreEqual(messageType, messageReceivedEventArgs.MessageType);
            Assert.AreEqual(message, messageReceivedEventArgs.Message);
        }
Ejemplo n.º 9
0
        public void DataReceived_MessageSplitInMultiplePackages_ReturnsCorrectMessage()
        {
            MessageType expectedMessageType = MessageType.Init;

            byte[] expectedBytes = new byte[] { 1, 2, 3, 4 };

            byte[] message = PacketProtocol <MessageType> .WrapMessage(expectedMessageType, expectedBytes);

            Assert.AreEqual(12, message.Length, "This test assumes the message length is 12");

            byte[] messagePackage1 = { message[0],
                                       message[1],
                                       message[2] };
            byte[] messagePackage2 = { message[3],
                                       message[4],
                                       message[5] };
            byte[] messagePackage3 = { message[6],
                                       message[7],
                                       message[8] };
            byte[] messagePackage4 = { message[9],
                                       message[10],
                                       message[11], };

            MessageType receivedMessageType = MessageType.Unknown;

            byte[] receivedBytes = null;

            PacketProtocol <MessageType> packetProtocol = new PacketProtocol <MessageType>(100);

            packetProtocol.MessageArrived += (type, bytes) =>
            {
                receivedMessageType = type;
                receivedBytes       = bytes;
            };

            packetProtocol.DataReceived(messagePackage1, messagePackage1.Length);
            Assert.AreEqual(MessageType.Unknown, receivedMessageType);
            packetProtocol.DataReceived(messagePackage2, messagePackage2.Length);
            Assert.AreEqual(MessageType.Unknown, receivedMessageType);
            packetProtocol.DataReceived(messagePackage3, messagePackage3.Length);
            Assert.AreEqual(MessageType.Unknown, receivedMessageType);

            packetProtocol.DataReceived(messagePackage4, messagePackage4.Length);

            Assert.AreEqual(expectedMessageType, receivedMessageType);
            Assert.AreEqual(expectedBytes, receivedBytes);
        }
        public void Send(TMessageType messageType, byte[] message)
        {
            if (_isDisposed)
            {
                throw new ObjectDisposedException("SocketConnectionController has been disposed");
            }

            byte[] data = PacketProtocol <TMessageType> .WrapMessage(messageType, message);

            // Begin sending the data to the remote device.
            try
            {
                _socket.BeginSendTo(data, 0, data.Length, 0, _targetEndPoint, SendCallback, data);
            }
            catch (SocketException e)
            {
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Sends message to remote client.
        /// </summary>
        /// <param name="client">Remote client socket object</param>
        /// <param name="data">Message to send</param>
        private static void Send(Socket client, Message data)
        {
            try
            {
                // convert message into byte array and wrap it for network transport:
                var    serializedMsg = Message.Serialize(data);
                byte[] byteData      = PacketProtocol.WrapMessage(serializedMsg);

                Debug.Log(String.Format("\t...almost send {0} bytes [{1}]", byteData.Length, data.Code));//-----------

                // Begin sending the data to the remote device:
                client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client);
            }
            catch (Exception ex)
            {
                Debug.Log(ex.ToString());
            }
        }
Ejemplo n.º 12
0
        public void Send_message_SendsMessage()
        {
            // Establish the local endpoint for the socket.
            IPHostEntry ipHostInfo    = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress   ipAddress     = ipHostInfo.AddressList[0];
            IPEndPoint  localEndPoint = new IPEndPoint(ipAddress, 20055);

            // Create a server
            Socket server = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            server.Bind(localEndPoint);
            server.Listen(2);

            // Create a SocketConnectionController
            int          clientId     = 0;
            StellaServer stellaServer = new StellaServer();

            stellaServer.Start(localEndPoint, 20056, clientId);

            Socket server_receiver = server.Accept();

            Thread.Sleep(1000);

            byte[] message      = Encoding.ASCII.GetBytes("ThisIsAMessage");
            byte[] expectedInit = PacketProtocol <MessageType> .WrapMessage(MessageType.Init, BitConverter.GetBytes(clientId));

            byte[] expectedMessage = PacketProtocol <MessageType> .WrapMessage(MessageType.Standard, message);

            // Expected init message
            byte[] receiveBufferInitMessage = new byte[expectedInit.Length];
            server_receiver.Receive(receiveBufferInitMessage);
            Assert.AreEqual(expectedInit, receiveBufferInitMessage);

            // Expected Standard message
            stellaServer.Send(MessageType.Standard, message);
            byte[] receiveBufferMessage = new byte[expectedMessage.Length];
            server_receiver.Receive(receiveBufferMessage);
            Assert.AreEqual(expectedMessage, receiveBufferMessage);
        }
        private void SendInternal(byte[] message)
        {
            if (_tcpClient == null)
            {
                return;
            }

            try
            {
                NetworkStream stream = _tcpClient.GetStream();
                if (stream.CanWrite)
                {
                    byte[] clientMessageAsByteArrayWrapped = PacketProtocol.WrapMessage(message);

                    stream.Write(clientMessageAsByteArrayWrapped, 0, clientMessageAsByteArrayWrapped.Length);
                    Debug.Log($"Message sent (size: {clientMessageAsByteArrayWrapped.Length})");
                }
            }
            catch (SocketException socketException)
            {
                Debug.LogError("Socket exception: " + socketException);
            }
        }
Ejemplo n.º 14
0
        public void SendCallback_SocketException_InvokesOnDisconnect()
        {
            MessageType messageType = MessageType.Init;

            byte[] message         = Encoding.ASCII.GetBytes("test message");
            byte[] expectedMessage = PacketProtocol <MessageType> .WrapMessage(messageType, message);

            var mock = new Mock <ISocketConnection>();

            mock.Setup(x => x.Connected).Returns(true);

            // Chain the BeginSend to the EndSend SendCallBack function
            mock.Setup(x => x.BeginSend(
                           It.IsAny <byte[]>(),
                           It.IsAny <int>(),
                           It.IsAny <int>(),
                           It.IsAny <SocketFlags>(),
                           It.IsAny <AsyncCallback>(),
                           It.IsAny <object>()))
            .Callback <byte[], int, int, SocketFlags, AsyncCallback, object>((data, offset, size, socketFlags, asyncCallback, state) =>
            {
                asyncCallback.Invoke(null);
            });

            mock.Setup(x => x.EndSend(It.IsAny <IAsyncResult>())).Throws <SocketException>();
            // Listen to the Disconnect event
            bool disconnectInvoked = false;
            SocketConnectionController <MessageType> controller = new SocketConnectionController <MessageType>(mock.Object, 1024);

            controller.Disconnect += (sender, args) => disconnectInvoked = true;

            // Run
            controller.Start();
            controller.Send(messageType, message);
            Assert.IsTrue(disconnectInvoked);
        }
Ejemplo n.º 15
0
        internal void SendMessageToAll(byte[] message)
        {
            var clientList =
                new ReadOnlyCollection <TcpClientInfo>((clientInfoStorage as TcpClientInfoStorage)
                                                       .ToList());

            Parallel.ForEach(clientList, client => WriteToAll(client));

            void WriteToAll(TcpClientInfo clientInfo)
            {
                try
                {
                    var bytes = PacketProtocol.WrapMessage(message);
                    clientInfo.Stream.WriteAsync(bytes, 0, bytes.Length);

                    Logger.LogDebug($"{bytes.Length } bytes sent to {clientInfo.ClientId}.");
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex.Message);
                    clientInfoStorage.RemoveInfo(clientInfo);
                }
            }
        }