Ejemplo n.º 1
0
        public bool CreateHandler(ArraySegment <byte> data)
        {
            var request = _parseRequest(data);

            if (request == null)
            {
                return(false);
            }

            Handler = _handlerFactory(this, request);
            if (Handler == null)
            {
                return(false);
            }

            ConnectionInfo = WebSocketConnectionInfo.Create(request, Socket.RemoteIpAddress, Socket.RemotePort);

            _initialize(this);

            var handshake = Handler.CreateHandshake();

            SendBytes(handshake, (instance, success) =>
            {
                if (success)
                {
                    instance.OnOpen();
                }
            });

            return(true);
        }
Ejemplo n.º 2
0
        public FleckWebSocketRequest(IWebSocketConnectionInfo connectionInfo, bool secure)
        {
            Cookies = new NameValueCollection();
            Form = new NameValueCollection();
            Headers = new NameValueCollection();
            QueryString = new NameValueCollection();

            string[] hostInfo = connectionInfo.Host.Split(':');
            string host = hostInfo[0];
            int port = Int32.Parse(hostInfo[1]);
            string[] pathInfo = connectionInfo.Path.Split('?');
            string path = pathInfo[0];
            string query = pathInfo[1];

            Url = new UriBuilder()
            {
                Scheme = secure ? "wss" : "ws",
                Host = host,
                Port = port,
                Path = path,
                Query = query
            }.Uri;

            ParseQuery(query);

            foreach (var cookie in connectionInfo.Cookies)
            {
                Cookies[cookie.Key] = cookie.Value;
            }
        }
 public FleckWebSocketConnection(int maxMessageSize)
     : base(maxMessageSize)
 {
     _connection = this;
     _context = new OwinWebSocketContext(_connection.Context, MaxMessageSize);
     _connectionInfo = new FleckWebSocketConnectionInfo(_connection.Context);
 }
 public FleckWebSocketConnection(int maxMessageSize)
     : base(maxMessageSize)
 {
     _connection     = this;
     _context        = new OwinWebSocketContext(_connection.Context, MaxMessageSize);
     _connectionInfo = new FleckWebSocketConnectionInfo(_connection.Context);
 }
Ejemplo n.º 5
0
        public void CreateHandler(IEnumerable <byte> data)
        {
            byte[] bytes   = data.ToArray();
            var    request = RequestParser.Parse(bytes, owner.Schema);

            if (request == null)
            {
                return;
            }
            handler = WebSocketHandlerFactory.BuildHandler(request, SockectConnection.OnMessage, SockectConnection.OnClose, SockectConnection.OnBinary);
            if (handler == null)
            {
                return;
            }
            var subProtocol = SubProtocolNegotiator.Negotiate(owner.SupportedSubProtocols, request.SubProtocols);

            ConnectionInfo = WebSocketConnectionInfo.Create(request, SockectConnection.Socket.RemoteIpAddress, SockectConnection.Socket.RemotePort, subProtocol);

            if (!string.IsNullOrEmpty(ConnectionInfo.Path))
            {
                SockectConnection.Session.Add("WebSocket_Path", ConnectionInfo.Path);
            }

            foreach (string item in ConnectionInfo.Cookies.Keys)
            {
                SockectConnection.Session.Add(item, ConnectionInfo.Cookies[item]);
            }

            var handshake = handler.CreateHandshake(subProtocol);

            SockectConnection.RawSend(handshake);
        }
Ejemplo n.º 6
0
        public FleckWebSocketRequest(IWebSocketConnectionInfo connectionInfo, bool secure)
        {
            Cookies     = new NameValueCollection();
            Form        = new NameValueCollection();
            Headers     = new NameValueCollection();
            QueryString = new NameValueCollection();

            string[] hostInfo = connectionInfo.Host.Split(':');
            string   host     = hostInfo[0];
            int      port     = Int32.Parse(hostInfo[1]);

            string[] pathInfo = connectionInfo.Path.Split('?');
            string   path     = pathInfo[0];
            string   query    = pathInfo[1];

            Url = new UriBuilder()
            {
                Scheme = secure ? "wss" : "ws",
                Host   = host,
                Port   = port,
                Path   = path,
                Query  = query
            }.Uri;

            ParseQuery(query);

            foreach (var cookie in connectionInfo.Cookies)
            {
                Cookies[cookie.Key] = cookie.Value;
            }
        }
Ejemplo n.º 7
0
        void clientConnected(IWebSocketConnection socket)
        {
            IWebSocketConnectionInfo info = socket.ConnectionInfo;

            connections.Add(socket);
            Console.WriteLine($"Client {info.Id} connected on {info.ClientIpAddress + ":" + info.ClientPort} ");
        }
Ejemplo n.º 8
0
 /// <summary>
 /// 删除定时器
 /// </summary>
 /// <param name="sender">消息源</param>
 /// <param name="connectionEventArgs">ConnectEventArgs</param>
 internal static ValueTask StopTimer(IWebSocketConnectionInfo sender, ConnectionEventArgs connectionEventArgs)
 {
     //停止计时器
     Timers[connectionEventArgs.SelfId].Dispose();
     Timers.Remove(connectionEventArgs.SelfId);
     ConsoleLog.Debug("SubTimer", $"Timer stopped user[{connectionEventArgs.SelfId}]");
     return(ValueTask.CompletedTask);
 }
Ejemplo n.º 9
0
        public FleckTransportDetails(IWebSocketConnectionInfo connectionInfo)
        {
            this.Type = "fleck_websocket";

            mConnectionInfo = connectionInfo;

            Peer = $"tcp4://{mConnectionInfo.ClientIpAddress}:{mConnectionInfo.ClientPort}";
        }
Ejemplo n.º 10
0
        public void Launch(Dictionary <GameNameType, IGame> games)
        {
            this.games = games;

            string serverAddress = string.Format("ws://{0}:{1}", this.ServerIp, this.ServerPort);

            FleckLog.Level = LogLevel.Debug;
            var server = new WebSocketServer(serverAddress);

            server.SupportedSubProtocols = new[] { "Hanabi" };

            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    IGame game = GetGame(socket);
                    if (game == null)
                    {
                        return;
                    }
                    IPlayer player = game.CreatePlayer(socket);
                    IWebSocketConnectionInfo connectionInfo = socket.ConnectionInfo;
                    allSockets.Add(connectionInfo.Id, player);
                };
                socket.OnClose = () =>
                {
                    IPlayer player = GetPlayer(socket);
                    if (player != null)
                    {
                        IGame game = player.Game;
                        if (game != null)
                        {
                            game.PlayerDisconnect(player);
                        }
                    }

                    IWebSocketConnectionInfo connectionInfo = socket.ConnectionInfo;
                    allSockets.Remove(connectionInfo.Id);
                };
                socket.OnMessage = (message) =>
                {
                    IPlayer player = null;
                    if (!allSockets.TryGetValue(socket.ConnectionInfo.Id, out player))
                    {
                        return;
                    }

                    IWebSocketConnection client = player.Client;
                    string subProtocol          = client.ConnectionInfo.SubProtocol;
                    IGame game = games.FirstOrDefault(pair => pair.Key.GameName == subProtocol).Value;
                    if (game != null)
                    {
                        game.DispatchRequest(player, message);
                    }
                };
            });
        }
        public FleckTransportDetails(IWebSocketConnectionInfo connectionInfo)
        {
            this.Type = "fleck_websocket";

            mConnectionInfo = connectionInfo;

            mPeer = string.Format("tcp4://{0}:{1}",
                                  mConnectionInfo.ClientIpAddress,
                                  mConnectionInfo.ClientPort);
        }
Ejemplo n.º 12
0
        private static CookieCollection GetCookieCollection(IWebSocketConnectionInfo connectionInfo)
        {
            CookieCollection result = new CookieCollection();

            foreach (KeyValuePair <string, string> cookie in connectionInfo.Cookies)
            {
                result.Add(new Cookie(cookie.Key, cookie.Value));
            }

            return(result);
        }
Ejemplo n.º 13
0
 /// <summary>
 /// 心跳包超时事件
 /// </summary>
 /// <param name="sender">连接信息</param>
 /// <param name="selfId">事件源</param>
 private void HeartBeatTimeOutEvent(long selfId, IWebSocketConnectionInfo sender)
 {
     if (OnHeartBeatTimeOut == null)
     {
         return;
     }
     Task.Run(async() =>
     {
         await OnHeartBeatTimeOut(sender,
                                  new ConnectionEventArgs("unknown", selfId));
     });
 }
Ejemplo n.º 14
0
        void clientDisconnected(IWebSocketConnection socket)
        {
            IWebSocketConnectionInfo info = socket.ConnectionInfo;

            connections.Remove(socket);
            Player disconnectedPlayer = dataManager.getPlayerById(info.Id.ToString());

            if (disconnectedPlayer != null)
            {
                dataManager.removePlayerById(info.Id.ToString());
            }
            Console.WriteLine($"Client {info.Id} closed on {info.ClientIpAddress + ":" + info.ClientPort} ");
        }
Ejemplo n.º 15
0
        async Task MainTask()
        {
            string ipv4 = GetLocalIPAddress();

            Console.WriteLine($"ws://{ipv4}:8181");
            server = new WebSocketServer($"ws://{ipv4}:8181");
            server.Start(socket =>
            {
                IWebSocketConnectionInfo info = socket.ConnectionInfo;
                socket.OnOpen    = () => clientConnected(socket);
                socket.OnClose   = () => clientDisconnected(socket);
                socket.OnMessage = message => parseMessage(message, socket);
            });
            updatePlayers();
            await Task.Delay(-1);
        }
Ejemplo n.º 16
0
        private void CreateHandler(IEnumerable <byte> data)
        {
            var request = _parseRequest(data.ToArray());

            if (request == null)
            {
                return;
            }
            Handler = _handlerFactory(request);
            if (Handler == null)
            {
                return;
            }
            ConnectionInfo = WebSocketConnectionInfo.Create(request, Socket.RemoteIpAddress);

            _initialize(this);

            var handshake = Handler.CreateHandshake();

            SendBytes(handshake, OnOpen);
        }
        private void CreateHandler(IEnumerable <byte> data)
        {
            var request = this.parser.Parse(data.ToArray(), this.scheme);

            if (request == null)
            {
                return;
            }

            try
            {
                this.Handler = HandlerFactory.BuildHandler(request);
            }
            catch (WebSocketException)
            {
                StandardHttpRequestReceivedEventArgs e = new StandardHttpRequestReceivedEventArgs(this);
                this.OnStandardHttpRequestReceived(e);
                if (!e.Handled)
                {
                    throw;
                }
            }

            if (this.Handler == null)
            {
                return;
            }

            this.Handler.TextMessageHandled   += new EventHandler <TextMessageHandledEventArgs>(this.Handler_TextMessageHandled);
            this.Handler.BinaryMessageHandled += new EventHandler <BinaryMessageHandledEventArgs>(this.Handler_BinaryMessageHandled);
            this.Handler.CloseHandled         += new EventHandler(this.Handler_CloseHandled);
            this.ConnectionInfo = WebSocketConnectionInfo.Create(request, this.Socket.RemoteIPAddress);

            var handshake = this.Handler.CreateHandshake();

            this.SendBytes(handshake);
            this.OnOpen(new ConnectionEventArgs(this));
        }
Ejemplo n.º 18
0
        async Task updatePlayers()
        {
            try
            {
                //checkRayCollisions(); disabled in favor of client sided hit detections
                foreach (IWebSocketConnection connection in connections)
                {
                    IWebSocketConnectionInfo info = connection.ConnectionInfo;
                    JArray playerArray            = new JArray();
                    foreach (Player player in dataManager.getPlayers())
                    {
                        if (!player.rayActive)
                        {
                            player.health = clampF(player.health + healthHeal, 0, player.maxHealth);
                            updateHealth(player.id, player.health, player.maxHealth);
                        }
                        if (player.id != info.Id.ToString())
                        {
                            JObject playerObject = createPlayerJObject(player.username, player.id, player.score, player.health, player.maxHealth, player.speed, player.size, player.realSpeed, player.position.x, player.position.y, player.ray.x, player.ray.y, player.rayActive);
                            playerArray.Add(playerObject);
                        }
                    }
                    JObject data = new JObject();
                    data.Add("players", playerArray);
                    JObject jsonObject = createStandardJObject("updatePlayers", data);
                    //Console.WriteLine(jsonObject.ToString());
                    connection.Send(jsonObject.ToString());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            await Task.Delay(updatePlayersDelay);

            updatePlayers();
        }
Ejemplo n.º 19
0
 public string GetUserId(IWebSocketConnectionInfo ConnectionInfo)
 {
     return(null);
 }
Ejemplo n.º 20
0
        void parseMessage(string message, IWebSocketConnection socket)
        {
            IWebSocketConnectionInfo info = socket.ConnectionInfo;

            //Console.WriteLine($"Received from {info.Id}: {message}");
            try
            {
                JObject jsonObject = JObject.Parse(message);
                string  type       = jsonObject.GetValue("type").ToString();
                JObject data       = (JObject)jsonObject.GetValue("data");
                if (type == "reportPlayer")
                {
                    Player player     = JSONToPlayer(data, info.Id.ToString());
                    Player realPlayer = dataManager.getPlayerById(info.Id.ToString());
                    player.health    = realPlayer.health;
                    player.maxHealth = realPlayer.maxHealth;
                    player.score     = realPlayer.score;
                    player.speed     = realPlayer.speed;
                    dataManager.updatePlayerById(info.Id.ToString(), player);
                }
                else if (type == "requestPlayer")
                {
                    string username = data.GetValue("username").ToString();
                    if (username.Length <= 15)
                    {
                        string bannedChars = @"<>/\";
                        foreach (char bannedChar in bannedChars)
                        {
                            username = username.Replace(bannedChar.ToString(), "");
                        }
                        if (username.Length == 0)
                        {
                            username = "******";
                        }
                        Point   spawnPoint = getSpawnPoint();
                        float   speed      = 1000;
                        JObject newPlayer  = createPlayerJObject(username, info.Id.ToString(), 0, 100, 100, speed, 50, 10, spawnPoint.x, spawnPoint.y, spawnPoint.x, spawnPoint.y, false);
                        newPlayer.Add("reportDelay", updatePlayersDelay);
                        JObject messageObj   = messageObject("setPlayer", newPlayer);
                        Vector2 spawnVector2 = new Vector2(spawnPoint.x, spawnPoint.y);
                        dataManager.addPlayer(new Player(username, info.Id.ToString(), 0, 100, 100, speed, 50, 10, spawnVector2, spawnVector2, false));
                        socket.Send(messageObj.ToString());
                    }
                }
                else if (type == "damagePlayer")
                {
                    string damagerId   = socket.ConnectionInfo.Id.ToString();
                    string recipientId = data.GetValue("recipientId").ToString();
                    Player player1     = dataManager.getPlayerById(damagerId);
                    Player player2     = dataManager.getPlayerById(recipientId);
                    if (distance(player1.position.x - player2.position.x, player1.position.y - player2.position.y) < 1200)
                    {
                        damagePlayer(damagerId, recipientId);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Ejemplo n.º 21
0
 public FleckCookieProvider(IWebSocketConnectionInfo connectionInfo) :
     base(GetCookieCollection(connectionInfo))
 {
 }
Ejemplo n.º 22
0
        private void CreateHandler(IEnumerable<byte> data)
        {
            var request = this.parser.Parse(data.ToArray(), this.scheme);
            if (request == null)
            {
                return;
            }

            try
            {
                this.Handler = HandlerFactory.BuildHandler(request);
            }
            catch (WebSocketException)
            {
                StandardHttpRequestReceivedEventArgs e = new StandardHttpRequestReceivedEventArgs(this);
                this.OnStandardHttpRequestReceived(e);
                if (!e.Handled)
                {
                    throw;
                }
            }

            if (this.Handler == null)
            {
                return;
            }

            this.Handler.TextMessageHandled += new EventHandler<TextMessageHandledEventArgs>(this.Handler_TextMessageHandled);
            this.Handler.BinaryMessageHandled += new EventHandler<BinaryMessageHandledEventArgs>(this.Handler_BinaryMessageHandled);
            this.Handler.CloseHandled += new EventHandler(this.Handler_CloseHandled);
            this.ConnectionInfo = WebSocketConnectionInfo.Create(request, this.Socket.RemoteIPAddress);

            var handshake = this.Handler.CreateHandshake();
            this.SendBytes(handshake);
            this.OnOpen(new ConnectionEventArgs(this));
        }