Пример #1
0
        private void AcceptTcpClientCallback(IAsyncResult ar)
        {
            TcpListener listenerInstance = (TcpListener)ar.AsyncState;

            TcpClient client = listenerInstance.EndAcceptTcpClient(ar);

            Console.WriteLine("WebSocketClient connected from " + client.Client.RemoteEndPoint);

            WebSocketTcpClient webSocketTcpClient = new WebSocketTcpClient(client, isSecureListener);

            webSocketTcpClient.OnDidClose += (endpoint, wsClient) =>
            {
                Console.WriteLine("Removing WebSocketClient ... " + endpoint);
                if (connectedWebSockets.Contains(webSocketTcpClient))
                {
                    connectedWebSockets.Remove(webSocketTcpClient);
                }
            };
            webSocketTcpClient.OnDidRead += (data) =>
            {
                OnReceiveBytes?.Invoke(data);
            };
            // TODO: Implement "CONNECTING" and "CONNECTED" states to limit
            // the number of "CONNECTING" requests from a specific client to "one"
            connectedWebSockets.Add(webSocketTcpClient);
            webSocketTcpClient.Start();

            // Wait for more clients
            listenerInstance.BeginAcceptTcpClient(AcceptTcpClientCallback, listenerInstance);
        }
        /// <summary>
        /// Receives this instance.
        /// </summary>
        private async void Receive()
        {
            while (true)
            {
                byte[] bytes;

                try
                {
                    bytes = await ReceiveBytesAsync(_cancellationTokenSource.Token).ConfigureAwait(false);
                }
                catch (OperationCanceledException)
                {
                    OnClosed();
                    break;
                }
                catch (Exception ex)
                {
                    _logger.LogError("Error receiving web socket message", ex);

                    break;
                }

                // Connection closed
                if (bytes == null)
                {
                    break;
                }

                OnReceiveBytes?.Invoke(bytes);
            }
        }