Esempio n. 1
0
        private void StartListenClient(TcpClientConnection connection, CancellationToken token)
        {
            _connections.TryAdd(connection.ConnectionId, connection);
            OnConnectionOpened(new TcpClientConnectionEventArgs(connection));

            try
            {
                while (!token.IsCancellationRequested)
                {
                    if (!connection.IsConnected())
                    {
                        break;
                    }

                    ITcpMessage message;

                    try
                    {
                        message = connection.ReadMessage();
                    }
                    catch (OperationCanceledException)
                    {
                        return;
                    }
                    catch (Exception)
                    {
                        connection.Disconnect();
                        OnConnectionClosed(new TcpClientConnectionEventArgs(connection));
                        break;
                    }

                    OnMessageReceived(new TcpMessageReceivedEventArgs(connection, message));
                }
            }
            finally
            {
                _connections.TryRemove(connection.ConnectionId, out var _);
            }
        }
Esempio n. 2
0
        private async Task ReceiveConnections(CancellationToken token)
        {
            try
            {
                while (!token.IsCancellationRequested)
                {
                    TcpClient client;

                    try
                    {
                        client = await _listener.AcceptTcpClientAsync(token);
                    }
                    catch (OperationCanceledException)
                    {
                        break;
                    }

                    if (_connections.Count == MaxConnectionsCount)
                    {
                        client.Close();
                        continue;
                    }

                    TcpClientConnection newConnection = ProcessConnection(client);
                    Task.Factory.StartNew(() => StartListenClient(newConnection, token), TaskCreationOptions.LongRunning);
                }
            }
            catch
            {
                ;
            }
            finally
            {
                _listener.Stop();
                OnServerStateChanged(new ServerStateEventArgs(State));
            }
        }
Esempio n. 3
0
 protected bool Equals(TcpClientConnection other)
 {
     return(Equals(Ip, other.Ip) && ConnectionId.Equals(other.ConnectionId));
 }