Beispiel #1
0
        public void WithData_SerializedDeserialized_Success()
        {
            var target = ServerGameStartedTransferMessage.Create()
                         .SetSize(43, 76);

            var parser = TransferMessageParserUtils.FindWriter(target);

            Assert.IsTrue(parser.IsWritable(target));
            var data = parser.Write(target);

            Console.WriteLine(data);
            var obj = (ServerGameStartedTransferMessage)parser.Read(data);

            Assert.AreEqual(target.Width, obj.Width);
            Assert.AreEqual(target.Height, obj.Height);
        }
Beispiel #2
0
        public void AllDataWithoutPlayerNameAndUnits_SerializedDeserialized_Success()
        {
            var target = ServerClientConnectedTransferMessage.Create()
                         .SetData(34, null, 43, 12);

            var parser = TransferMessageParserUtils.FindWriter(target);

            Assert.IsTrue(parser.IsWritable(target));
            var data = parser.Write(target);

            Console.WriteLine(data);
            var obj = (ServerClientConnectedTransferMessage)parser.Read(data);

            Assert.AreEqual(target.CurrentCount, obj.CurrentCount);
            Assert.AreEqual(target.PlayerId, obj.PlayerId);
            Assert.AreEqual(target.PlayerName, obj.PlayerName);
            Assert.AreEqual(target.WaitingCount, obj.WaitingCount);
        }
Beispiel #3
0
        public void NoSkills_SerializedDeserialized_Success()
        {
            var target = ClientConnectTransferMessage.Create()
                         .SetPlayerName("Player1")
                         .AddUnitType(UnitUtils.UnitType.Mage);

            var parser = TransferMessageParserUtils.FindWriter(target);

            Assert.IsTrue(parser.IsWritable(target));
            var data = parser.Write(target);

            Console.WriteLine(data);
            var obj = (ClientConnectTransferMessage)parser.Read(data);

            Assert.AreEqual(target.PlayerName, obj.PlayerName);
            Assert.AreEqual(target.UnitsData.Count, obj.UnitsData.Count);
            Assert.AreEqual(target.UnitsData[0].UnitType, obj.UnitsData[0].UnitType);
            Assert.AreEqual(target.UnitsData[0].Skills, obj.UnitsData[0].Skills);
        }
        public void WithoutData_SerializedDeserialized_Success()
        {
            var target = ServerCurrentStateTransferMessage.Create()
                         .AddPlayer(43, 2, 3);

            var parser = TransferMessageParserUtils.FindWriter(target);

            Assert.IsTrue(parser.IsWritable(target));
            var data = parser.Write(target);

            Console.WriteLine(data);
            var obj = (ServerCurrentStateTransferMessage)parser.Read(data);

            Assert.AreEqual(target.Doors, obj.Doors);
            Assert.AreEqual(target.Exit, obj.Exit);
            Assert.AreEqual(target.Players.Count, obj.Players.Count);
            Assert.AreEqual(target.Players[0].PlayerId, obj.Players[0].PlayerId);
            Assert.AreEqual(target.Players[0].Units, obj.Players[0].Units);
            Assert.AreEqual(target.Map, obj.Map);
        }
Beispiel #5
0
        public void AllDataWithPlayerName_SerializedDeserialized_Success()
        {
            var target = ServerClientConnectedTransferMessage.Create()
                         .SetData(34, "Player1", 43, 12)
                         .AddUnit(16, UnitUtils.UnitType.Warrior);

            var parser = TransferMessageParserUtils.FindWriter(target);

            Assert.IsTrue(parser.IsWritable(target));
            var data = parser.Write(target);

            Console.WriteLine(data);
            var obj = (ServerClientConnectedTransferMessage)parser.Read(data);

            Assert.AreEqual(target.CurrentCount, obj.CurrentCount);
            Assert.AreEqual(target.PlayerId, obj.PlayerId);
            Assert.AreEqual(target.PlayerName, obj.PlayerName);
            Assert.AreEqual(target.WaitingCount, obj.WaitingCount);
            Assert.AreEqual(target.Units.Count, obj.Units.Count);
            Assert.AreEqual(target.Units[0].UnitId, obj.Units[0].UnitId);
            Assert.AreEqual(target.Units[0].UnitType, obj.Units[0].UnitType);
        }
Beispiel #6
0
        public void WithData_SerializedDeserialized_Success()
        {
            var target = ServerYouConnectedTransferMessage.Create()
                         .SetPlayerId(35)
                         .AddUnit(3, UnitUtils.UnitType.Ranger, 2, 1, 0, 0, true, 0, 0, 0);

            var parser = TransferMessageParserUtils.FindWriter(target);

            Assert.IsTrue(parser.IsWritable(target));
            var data = parser.Write(target);

            Console.WriteLine(data);
            var obj = (ServerYouConnectedTransferMessage)parser.Read(data);

            Assert.AreEqual(target.PlayerId, obj.PlayerId);
            Assert.AreEqual(target.UnitsData.Count, obj.UnitsData.Count);
            Assert.AreEqual(target.UnitsData[0].UnitType, obj.UnitsData[0].UnitType);
            Assert.AreEqual(target.UnitsData[0].VisionRange, obj.UnitsData[0].VisionRange);
            Assert.AreEqual(target.UnitsData[0].MoveRange, obj.UnitsData[0].MoveRange);
            Assert.AreEqual(target.UnitsData[0].UnitId, obj.UnitsData[0].UnitId);
            Assert.AreEqual(target.UnitsData[0].AttackFriendlyFire, obj.UnitsData[0].AttackFriendlyFire);
        }
        public void NewPositionExists_SerializedDeserialized_Success()
        {
            var target = ClientTurnDoneTransferMessage.Create()
                         .SetNewPosition(1, 11, 12)
                         .SetNewPosition(3, 12, 11)
                         .SetNewPosition(11, 110, 0);

            var parser = TransferMessageParserUtils.FindWriter(target);

            Assert.IsTrue(parser.IsWritable(target));
            var data = parser.Write(target);

            Console.WriteLine(data);
            var obj = (ClientTurnDoneTransferMessage)parser.Read(data);

            Assert.AreEqual(target.UnitActions.Count, obj.UnitActions.Count);
            Assert.AreEqual(target.UnitActions[1].NewPosition.X, obj.UnitActions[1].NewPosition.X);
            Assert.AreEqual(target.UnitActions[1].NewPosition.Y, obj.UnitActions[1].NewPosition.Y);
            Assert.AreEqual(target.UnitActions[3].NewPosition.X, obj.UnitActions[3].NewPosition.X);
            Assert.AreEqual(target.UnitActions[3].NewPosition.Y, obj.UnitActions[3].NewPosition.Y);
            Assert.AreEqual(target.UnitActions[11].NewPosition.X, obj.UnitActions[11].NewPosition.X);
            Assert.AreEqual(target.UnitActions[11].NewPosition.Y, obj.UnitActions[11].NewPosition.Y);
        }
        protected override void DoAction(Entity entity, TimeSpan gameTime)
        {
            base.DoAction(entity, gameTime);
            var localClient  = entity.GetComponent <LocalClientComponent>();
            var client       = entity.GetComponent <ClientComponent>();
            var serverEntity = this.scene.FindEntity(localClient.ServerEntity);
            var localServer  = serverEntity.GetComponent <LocalServerComponent>();

            if (localClient.Identifier == Guid.Empty)
            {
                localClient.Identifier = Guid.NewGuid();
                localServer.PendingConnections.Add(localClient.Identifier);
                return;
            }

            if (client.Message != null)
            {
                var transferMessage = client.Message;
                var parser          = TransferMessageParserUtils.FindWriter(transferMessage, this.parsers);
                var data            = parser.Write(transferMessage);
                localServer.Request[localClient.Identifier].Enqueue(data);
                (client.Message as IPoolableTransferMessage)?.Free();
                client.Message = null;
            }

            var response = localServer.Response[localClient.Identifier];

            (client.Response as IPoolableTransferMessage)?.Free();
            client.Response = null;
            if (response.Count > 0)
            {
                var data            = response.Dequeue();
                var parser          = TransferMessageParserUtils.FindReader(data, parsers);
                var transferMessage = parser.Read(data);
                client.Response = transferMessage;
            }
        }
        protected override void DoAction(Entity entity, TimeSpan gameTime)
        {
            base.DoAction(entity, gameTime);
#if Bridge
            System.Diagnostics.Debug.WriteLine("Network server is not available for web version.");
#else
            var networkServer = entity.GetComponent <NetworkServerComponent>();
            var server        = entity.GetComponent <ServerComponent>();

            if (networkServer.Listener == null)
            {
                networkServer.Listener = new TcpListener(IPAddress.Parse(networkServer.Ip), networkServer.Port);
                networkServer.Listener.Start();
            }

            if (networkServer.ConnectResult == null)
            {
                networkServer.ConnectResult = networkServer.Listener.BeginAcceptTcpClient((a) => { }, null);
            }

            if (networkServer.ConnectResult.IsCompleted)
            {
                server.ConnectedPlayers++;
                var tcpClient = networkServer.Listener.EndAcceptTcpClient(networkServer.ConnectResult);
                networkServer.Clients.Add(tcpClient);
                networkServer.ConnectionKeyToClient[server.ConnectedPlayers] = tcpClient;
                networkServer.ClientToConnectionKey[tcpClient] = server.ConnectedPlayers;
                server.Request[networkServer.ClientToConnectionKey[tcpClient]]  = new Queue <ITransferMessage>();
                server.Response[networkServer.ClientToConnectionKey[tcpClient]] = new Queue <ITransferMessage>();
                networkServer.ConnectResult = null;
            }

            for (var i = 0; i < networkServer.Clients.Count; i++)
            {
                var tcpClient     = networkServer.Clients[i];
                var connectionKey = networkServer.ClientToConnectionKey[tcpClient];
                if (tcpClient.Available > 0)
                {
                    byte[] bytes = new byte[tcpClient.Available];
                    tcpClient.GetStream().Read(bytes, 0, tcpClient.Available);
                    string data = Encoding.UTF8.GetString(bytes);

                    if (Regex.IsMatch(data, "^GET", RegexOptions.IgnoreCase))
                    {
                        // 1. Obtain the value of the "Sec-WebSocket-Key" request header without any leading or trailing whitespace
                        // 2. Concatenate it with "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (a special GUID specified by RFC 6455)
                        // 3. Compute SHA-1 and Base64 hash of the new value
                        // 4. Write the hash back as the value of "Sec-WebSocket-Accept" response header in an HTTP response
                        string swk            = Regex.Match(data, "Sec-WebSocket-Key: (.*)").Groups[1].Value.Trim();
                        string swka           = swk + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
                        byte[] swkaSha1       = System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(swka));
                        string swkaSha1Base64 = Convert.ToBase64String(swkaSha1);

                        var value = "HTTP/1.1 101 Switching Protocols\r\n" +
                                    "Connection: Upgrade\r\n" +
                                    "Upgrade: websocket\r\n" +
                                    "Sec-WebSocket-Accept: " + swkaSha1Base64 + "\r\n\r\n";
                        byte[] responseBytes = Encoding.UTF8.GetBytes(value);
                        tcpClient.GetStream().Write(responseBytes, 0, value.Length);
                        continue;
                    }

                    data = Encoding.UTF8.GetString(GetDecodedData(bytes, bytes.Length));
                    var parser          = TransferMessageParserUtils.FindReader(data, parsers);
                    var transferMessage = parser.Read(data);
                    server.Request[connectionKey].Enqueue(transferMessage);
                    continue;
                }

                var response = server.Response[connectionKey];
                if (response.Count > 0)
                {
                    var transferMessage = response.Dequeue();
                    var parser          = TransferMessageParserUtils.FindWriter(transferMessage, parsers);
                    var data            = parser.Write(transferMessage);
                    (transferMessage as IPoolableTransferMessage)?.Free();
                    byte[] frame = GetFrameFromBytes(Encoding.UTF8.GetBytes(data));

                    tcpClient.GetStream().Write(frame, 0, frame.Length);
                    tcpClient.GetStream().Flush();
                    return;
                }
            }
#endif
        }
        protected override void DoAction(Entity entity, TimeSpan gameTime)
        {
            base.DoAction(entity, gameTime);
            var networkClient = entity.GetComponent <NetworkClientComponent>();
            var client        = entity.GetComponent <ClientComponent>();

            if (networkClient.Client == null)
            {
                networkClient.Client = new ClientWebSocket();
                networkClient.Client.ConnectAsync(networkClient.ServerAddress, CancellationToken.None);
            }

            if (networkClient.Client.State != WebSocketState.Open)
            {
                return;
            }

            (client.Response as IPoolableTransferMessage)?.Free();
            client.Response = null;

            if (client.Message != null)
            {
                var transferMessage = client.Message;
                var parser          = TransferMessageParserUtils.FindWriter(transferMessage, parsers);
                var data            = parser.Write(transferMessage);
                networkClient.Client.SendAsync(
                    new ArraySegment <byte>(Encoding.UTF8.GetBytes(data)),
                    WebSocketMessageType.Text,
                    true,
                    CancellationToken.None);
                (client.Message as IPoolableTransferMessage)?.Free();
                client.Message = null;
                return;
            }

            if (networkClient.RecievingTask == null)
            {
                networkClient.RecievingTask = networkClient.Client.ReceiveAsync(networkClient.RecievingBuffer, CancellationToken.None);
            }

            if (networkClient.RecievingTask.IsCompleted)
            {
                var result = networkClient.RecievingTask.Result;
                networkClient.RecievingTask = null;
                ms.Seek(0, SeekOrigin.Begin);
                ms.SetLength(0);
                ms.Write(networkClient.RecievingBuffer.Array, networkClient.RecievingBuffer.Offset, result.Count);

                while (!result.EndOfMessage)
                {
                    result = networkClient.Client.ReceiveAsync(networkClient.RecievingBuffer, CancellationToken.None).Result;
                    ms.Write(networkClient.RecievingBuffer.Array, networkClient.RecievingBuffer.Offset, result.Count);
                }
                ;


                ms.Seek(0, SeekOrigin.Begin);
                var data = reader.ReadToEnd();

                var parser          = TransferMessageParserUtils.FindReader(data, parsers);
                var transferMessage = parser.Read(data);
                client.Response = transferMessage;
            }
        }