private async void Process(System.Net.Sockets.TcpClient client)
        {
            var clientId = _nextClientId++;

            var wsClient = new WebSocketClient(client)
            {
                Id           = clientId,
                ServerClient = true
            };

            Clients.Add(wsClient);

            OnClientConnected(wsClient);

            try
            {
                //check if it's a websocket connection
                while (client.Connected)
                {
                    if (await ProcessWebsocketUpgrade(wsClient).ConfigureAwait(false))
                    {
                        wsClient.UpgradedConnection = true;
                        break;
                    }
                    else
                    {
                        await Task.Delay(50).ConfigureAwait(false);
                    }
                }

                while (client.IsConnected())
                {
                    var messages = await wsClient.GetMessages().ConfigureAwait(false);

                    ProcessMessage(wsClient, messages);
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }

            client?.Dispose();

            Clients.Remove(wsClient);
        }
        private async Task <bool> ProcessWebsocketUpgrade(WebSocketClient client)
        {
            var message = await client.GetHttpRequest().ConfigureAwait(false);

            if (message?.StartsWith("GET") ?? false)
            {
                if (!GetAuthentication(message))
                {
                    return(false);
                }

                if (!new Regex("Connection:(.*)").Match(message).Groups[1].Value.Trim().StartsWith("Upgrade"))
                {
                    return(false);
                }

                var response = CreateWebsocketUpgradeReponse(message);
                await client.SendRawData(response).ConfigureAwait(false);

                return(true);
            }

            return(false);
        }
        private void ProcessConnection(WebSocketClient client)
        {
            try
            {
                client.UpgradedConnection = ProcessWebsocketUpgrade(client);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

                client?.Dispose();

                Clients.Remove(client);

                return;
            }

            if (client.UpgradedConnection)
            {
                Task
                .Delay(ClientUpgradeTimeout)
                .ContinueWith(t => OnClientConnected(client));
            }
        }
예제 #4
0
 protected void OnClientConnected(WebSocketClient client)
 {
     Task.Run(() => ClientConnected?.Invoke(this, client));
 }