Ejemplo n.º 1
0
        public void SendToAllTest()
        {
            // listen
            NetworkServer.Listen(1);
            Assert.That(NetworkServer.connections.Count, Is.EqualTo(0));

            // add connection
            ULocalConnectionToClient connection = new ULocalConnectionToClient();

            connection.connectionToServer = new ULocalConnectionToServer();
            // set a client handler
            int called = 0;

            connection.connectionToServer.SetHandlers(new Dictionary <int, NetworkMessageDelegate>()
            {
                { MessagePacker.GetId <TestMessage1>(), ((conn, reader, channelId) => ++ called) }
            });
            NetworkServer.AddConnection(connection);

            // create a message
            TestMessage1 message = new TestMessage1 {
                IntValue = 1, DoubleValue = 2, StringValue = "3"
            };

            // send it to all
            NetworkServer.SendToAll(message);

            // update local connection once so that the incoming queue is processed
            connection.connectionToServer.Update();

            // was it send to and handled by the connection?
            Assert.That(called, Is.EqualTo(1));
        }
Ejemplo n.º 2
0
        public void FindSystemMessage()
        {
            var id   = MessagePacker.GetId <SceneMessage>();
            var type = MessagePacker.MessageTypes[id];

            Assert.That(type, Is.EqualTo(typeof(SceneMessage)));
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Replaces a handler for a particular message type.
 /// <para>See also <see cref="RegisterHandler{T}(Action{NetworkConnection, T}, bool)">RegisterHandler(T)(Action(NetworkConnection, T), bool)</see></para>
 /// </summary>
 /// <typeparam name="T">Message type</typeparam>
 /// <param name="handler">Function handler which will be invoked when this message type is received.</param>
 /// <param name="requireAuthentication">True if the message requires an authenticated connection</param>
 public void ReplaceHandler<T>(Action<T> handler, bool requireAuthentication = true) where T : struct, NetworkMessage
 {
     int msgType = MessagePacker.GetId<T>();
     if (typeof(T) == typeof(ConnectMessage))
     {
         NetworkClient.ReplaceHandler<ConnectMessage>((conn, msg) => {
             OnClientConnect(conn, msg);
             handler((T)(msg as NetworkMessage));
         },
             requireAuthentication
         );
     }
     else if (typeof(T) == typeof(DisconnectMessage))
     {
         NetworkClient.ReplaceHandler<DisconnectMessage>((conn, msg) => {
             OnClientDisconnect(conn, msg);
             handler((T)(msg as NetworkMessage));
         },
             requireAuthentication
         );
     }
     else
     {
         NetworkClient.RegisterHandler<T>(handler, requireAuthentication);
     }
 }
Ejemplo n.º 4
0
        public void FindSystemMessage()
        {
            int  id   = MessagePacker.GetId <SceneMessage>();
            Type type = MessagePacker.GetMessageType(id);

            Assert.That(type, Is.EqualTo(typeof(SceneMessage)));
        }
Ejemplo n.º 5
0
        public void ClientToServerTest()
        {
            MyMessage myMessage = new MyMessage()
            {
                id   = 3,
                name = "hello"
            };

            bool invoked = false;

            void handler(NetworkMessage msg)
            {
                MyMessage received = msg.ReadMessage <MyMessage>();

                Assert.That(received.id, Is.EqualTo(3));
                Assert.That(received.name, Is.EqualTo("hello"));
                invoked = true;
            }

            Dictionary <int, NetworkMessageDelegate> handlers = new Dictionary <int, NetworkMessageDelegate>();

            handlers.Add(MessagePacker.GetId <MyMessage>(), handler);

            connectionToServer.SetHandlers(handlers);
            connectionToClient.Send(myMessage);

            connectionToServer.Update();

            Assert.True(invoked, "handler should have been invoked");
        }
Ejemplo n.º 6
0
        public void ClientToServerTest()
        {
            var myMessage = new MyMessage
            {
                id   = 3,
                name = "hello"
            };

            bool invoked = false;

            void handler(NetworkConnection conn, NetworkReader reader, int channelId)
            {
                var received = new MyMessage();

                received.Deserialize(reader);
                Assert.That(received.id, Is.EqualTo(3));
                Assert.That(received.name, Is.EqualTo("hello"));
                invoked = true;
            }

            var handlers = new Dictionary <int, NetworkMessageDelegate>
            {
                { MessagePacker.GetId <MyMessage>(), handler }
            };

            connectionToServer.SetHandlers(handlers);
            connectionToClient.Send(myMessage);

            connectionToServer.Update();

            Assert.True(invoked, "handler should have been invoked");
        }
Ejemplo n.º 7
0
 public void ThrowsWhenNoHandlerIsFound()
 {
     ExpectLog(() =>
     {
         int messageId = MessagePacker.GetId <SceneMessage>();
         messageHandler.InvokeHandler(player, messageId, reader);
     }
               , $"Unexpected message {typeof(SceneMessage)} received from {player}. Did you register a handler for it?");
 }
Ejemplo n.º 8
0
        public void RegisterMessage()
        {
            MessagePacker.RegisterMessage <SomeRandomMessage>();

            int id = MessagePacker.GetId <SomeRandomMessage>();

            Type type = MessagePacker.GetMessageType(id);

            Assert.That(type, Is.EqualTo(typeof(SomeRandomMessage)));
        }
Ejemplo n.º 9
0
        public void RegisterMessage()
        {
            MessagePacker.RegisterMessage <SomeRandomMessage>();

            var id = MessagePacker.GetId <SomeRandomMessage>();

            var type = MessagePacker.MessageTypes[id];

            Assert.That(type, Is.EqualTo(typeof(SomeRandomMessage)));
        }
Ejemplo n.º 10
0
        public void FindUnknownMessage()
        {
            // note that GetId<> will cause the weaver to register it
            // but GetId() will not
            int id = MessagePacker.GetId(typeof(SomeRandomMessageNotRegistered));

            Assert.Throws <KeyNotFoundException>(() =>
            {
                _ = MessagePacker.GetMessageType(id);
            });
        }
Ejemplo n.º 11
0
        public void NoHandler()
        {
            int messageId = MessagePacker.GetId <SceneMessage>();
            var reader    = new NetworkReader(new byte[] { 1, 2, 3, 4 });
            InvalidDataException exception = Assert.Throws <InvalidDataException>(() =>
            {
                connection.InvokeHandler(messageId, reader, 0);
            });

            Assert.That(exception.Message, Does.StartWith("Unexpected message Mirage.SceneMessage received"));
        }
Ejemplo n.º 12
0
        public void UnknownMessage()
        {
            _ = MessagePacker.GetId <SceneMessage>();
            var reader = new NetworkReader(new byte[] { 1, 2, 3, 4 });
            InvalidDataException exception = Assert.Throws <InvalidDataException>(() =>
            {
                // some random id with no message
                connection.InvokeHandler(1234, reader, 0);
            });

            Assert.That(exception.Message, Does.StartWith("Unexpected message ID 1234 received"));
        }
Ejemplo n.º 13
0
        public void ShowForConnection()
        {
            // message handlers
            NetworkServer.RegisterHandler <ConnectMessage>((conn, msg) => { }, false);
            NetworkServer.RegisterHandler <DisconnectMessage>((conn, msg) => { }, false);
            NetworkServer.RegisterHandler <ErrorMessage>((conn, msg) => { }, false);

            // listen
            NetworkServer.Listen(1);
            Assert.That(NetworkServer.connections.Count, Is.EqualTo(0));

            // add connection
            ULocalConnectionToClient connection = new ULocalConnectionToClient();

            // required for ShowForConnection
            connection.isReady            = true;
            connection.connectionToServer = new ULocalConnectionToServer();
            // set a client handler
            int called = 0;

            connection.connectionToServer.SetHandlers(new Dictionary <int, NetworkMessageDelegate>()
            {
                { MessagePacker.GetId <SpawnMessage>(), ((conn, reader, channelId) => ++ called) }
            });
            NetworkServer.AddConnection(connection);

            // create a gameobject and networkidentity and some unique values
            NetworkIdentity identity = new GameObject().AddComponent <NetworkIdentity>();

            identity.connectionToClient = connection;

            // call ShowForConnection
            NetworkServer.ShowForConnection(identity, connection);

            // update local connection once so that the incoming queue is processed
            connection.connectionToServer.Update();

            // was it sent to and handled by the connection?
            Assert.That(called, Is.EqualTo(1));

            // it shouldn't send it if connection isn't ready, so try that too
            connection.isReady = false;
            NetworkServer.ShowForConnection(identity, connection);
            connection.connectionToServer.Update();
            // not 2 but 1 like before?
            Assert.That(called, Is.EqualTo(1));

            // clean up
            NetworkServer.Shutdown();
            // destroy GO after shutdown, otherwise isServer is true in OnDestroy and it tries to call
            // GameObject.Destroy (but we need DestroyImmediate in Editor)
            GameObject.DestroyImmediate(identity.gameObject);
        }
Ejemplo n.º 14
0
        public void InvokesMessageHandler()
        {
            int invoked = 0;

            messageHandler.RegisterHandler <SceneReadyMessage>(_ => { invoked++; });

            int messageId = MessagePacker.GetId <SceneReadyMessage>();

            messageHandler.InvokeHandler(player, messageId, reader);

            Assert.That(invoked, Is.EqualTo(1), "Should have been invoked");
        }
Ejemplo n.º 15
0
        public void SendToClientOfPlayer()
        {
            // message handlers
            NetworkServer.RegisterHandler <ConnectMessage>((conn, msg) => { }, false);
            NetworkServer.RegisterHandler <DisconnectMessage>((conn, msg) => { }, false);
            NetworkServer.RegisterHandler <ErrorMessage>((conn, msg) => { }, false);

            // listen
            NetworkServer.Listen(1);
            Assert.That(NetworkServer.connections.Count, Is.EqualTo(0));

            // add connection
            ULocalConnectionToClient connection = new ULocalConnectionToClient();

            connection.connectionToServer = new ULocalConnectionToServer();
            // set a client handler
            int called = 0;

            connection.connectionToServer.SetHandlers(new Dictionary <int, NetworkMessageDelegate>()
            {
                { MessagePacker.GetId <TestMessage>(), ((conn, reader, channelId) => ++ called) }
            });
            NetworkServer.AddConnection(connection);

            // create a message
            TestMessage message = new TestMessage {
                IntValue = 1, DoubleValue = 2, StringValue = "3"
            };

            // create a gameobject and networkidentity
            NetworkIdentity identity = new GameObject().AddComponent <NetworkIdentity>();

            identity.connectionToClient = connection;

            // send it to that player
            NetworkServer.SendToClientOfPlayer(identity, message);

            // update local connection once so that the incoming queue is processed
            connection.connectionToServer.Update();

            // was it send to and handled by the connection?
            Assert.That(called, Is.EqualTo(1));

            // clean up
            NetworkServer.Shutdown();
            // destroy GO after shutdown, otherwise isServer is true in OnDestroy and it tries to call
            // GameObject.Destroy (but we need DestroyImmediate in Editor)
            GameObject.DestroyImmediate(identity.gameObject);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// This function invokes the registered handler function for a message.
        /// <para>Network connections used by the NetworkClient and NetworkServer use this function for handling network messages.</para>
        /// </summary>
        /// <typeparam name="T">The message type to unregister.</typeparam>
        /// <param name="msg">The message object to process.</param>
        /// <returns>Returns true if the handler was successfully invoked</returns>
        public bool InvokeHandler<T>(T msg, int channelId) where T :struct, NetworkMessage
        {
            using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter())
            {
                // if it is a value type,  just use typeof(T) to avoid boxing
                // this works because value types cannot be derived
                // if it is a reference type (for example NetworkMessage),
                // ask the message for the real type
                int msgType = MessagePacker.GetId<T>();

                MessagePacker.Pack(msg, writer);
                ArraySegment<byte> segment = writer.ToArraySegment();
                using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(segment))
                    return InvokeHandler(msgType, networkReader, channelId);
            }
        }
Ejemplo n.º 17
0
        // unpack a message we received
        public static T UnpackFromByteArray <T>(byte[] data)
            where T : struct, NetworkMessage
        {
            using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(data))
            {
                int msgType = MessagePacker.GetId <T>();

                int id = networkReader.ReadUInt16();
                if (id != msgType)
                {
                    throw new FormatException("Invalid message,  could not unpack " + typeof(T).FullName);
                }

                return(networkReader.Read <T>());
            }
        }
Ejemplo n.º 18
0
        public void SendToAllTest()
        {
            // message handlers
            NetworkServer.RegisterHandler <ConnectMessage>((conn, msg) => {}, false);
            NetworkServer.RegisterHandler <DisconnectMessage>((conn, msg) => {}, false);
            NetworkServer.RegisterHandler <ErrorMessage>((conn, msg) => {}, false);

            // listen
            NetworkServer.Listen(1);
            Assert.That(NetworkServer.connections.Count, Is.EqualTo(0));

            // add connection
            ULocalConnectionToClient connection = new ULocalConnectionToClient();

            connection.connectionToServer = new ULocalConnectionToServer();
            // set a client handler
            int called = 0;

            connection.connectionToServer.SetHandlers(new Dictionary <int, NetworkMessageDelegate>()
            {
                { MessagePacker.GetId <TestMessage>(), (msg => ++ called) }
            });
            NetworkServer.AddConnection(connection);

            // create a message
            TestMessage message = new TestMessage {
                IntValue = 1, DoubleValue = 2, StringValue = "3"
            };

            // send it to all
            bool result = NetworkServer.SendToAll(message);

            Assert.That(result, Is.True);

            // update local connection once so that the incoming queue is processed
            connection.connectionToServer.Update();

            // was it send to and handled by the connection?
            Assert.That(called, Is.EqualTo(1));

            // clean up
            NetworkServer.Shutdown();
        }
Ejemplo n.º 19
0
        public void HideForConnection()
        {
            // listen
            NetworkServer.Listen(1);
            Assert.That(NetworkServer.connections.Count, Is.EqualTo(0));

            // add connection
            ULocalConnectionToClient connection = new ULocalConnectionToClient();

            // required for ShowForConnection
            connection.isReady            = true;
            connection.connectionToServer = new ULocalConnectionToServer();
            // set a client handler
            int called = 0;

            connection.connectionToServer.SetHandlers(new Dictionary <int, NetworkMessageDelegate>()
            {
                { MessagePacker.GetId <ObjectHideMessage>(), ((conn, reader, channelId) => ++ called) }
            });
            NetworkServer.AddConnection(connection);

            // create a gameobject and networkidentity
            NetworkIdentity identity = new GameObject().AddComponent <NetworkIdentity>();

            identity.connectionToClient = connection;

            // call HideForConnection
            NetworkServer.HideForConnection(identity, connection);

            // update local connection once so that the incoming queue is processed
            connection.connectionToServer.Update();

            // was it sent to and handled by the connection?
            Assert.That(called, Is.EqualTo(1));

            // clean up
            NetworkServer.Shutdown();
            // destroy GO after shutdown, otherwise isServer is true in OnDestroy and it tries to call
            // GameObject.Destroy (but we need DestroyImmediate in Editor)
            GameObject.DestroyImmediate(identity.gameObject);
        }