Ejemplo n.º 1
0
        protected override void DoAction(Entity entity, System.TimeSpan gameTime)
        {
            base.DoAction(entity, gameTime);
            var localServer = entity.GetComponent <LocalServerComponent>();
            var server      = entity.GetComponent <ServerComponent>();

            if (localServer.PendingConnections.Count > 0)
            {
                for (var i = 0; i < localServer.PendingConnections.Count; i++)
                {
                    server.ConnectedPlayers++;
                    var tcpClient = localServer.PendingConnections[i];
                    localServer.Clients.Add(tcpClient);
                    localServer.ConnectionKeyToClient[server.ConnectedPlayers] = tcpClient;
                    localServer.ClientToConnectionKey[tcpClient] = server.ConnectedPlayers;
                    server.Request[localServer.ClientToConnectionKey[tcpClient]]  = new Queue <ITransferMessage>();
                    server.Response[localServer.ClientToConnectionKey[tcpClient]] = new Queue <ITransferMessage>();
                    localServer.Request[tcpClient]  = new Queue <string>();
                    localServer.Response[tcpClient] = new Queue <string>();
                }
                localServer.PendingConnections.Clear();
            }

            for (var i = 0; i < localServer.Clients.Count; i++)
            {
                var client        = localServer.Clients[i];
                var connectionKey = localServer.ClientToConnectionKey[client];
                if (localServer.Request.ContainsKey(client) && localServer.Request[client].Count > 0)
                {
                    var request = localServer.Request[client];
                    while (request.Count > 0)
                    {
                        var data            = request.Dequeue();
                        var parser          = TransferMessageParserUtils.FindReader(data, parsers);
                        var transferMessage = parser.Read(data);
                        server.Request[connectionKey].Enqueue(transferMessage);
                    }
                }

                if (server.Response.ContainsKey(connectionKey) && server.Response[connectionKey].Count > 0)
                {
                    var response = server.Response[connectionKey];
                    while (response.Count > 0)
                    {
                        var transferMessage = response.Dequeue();
                        var parser          = TransferMessageParserUtils.FindWriter(transferMessage, parsers);
                        var data            = parser.Write(transferMessage);
                        localServer.Response[client].Enqueue(data);
                        (transferMessage as IPoolableTransferMessage)?.Free();
                    }
                }
            }
        }
        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;
            }
        }