Ejemplo n.º 1
0
        /// <summary>
        /// Try to connect to a TcpClient.
        /// If can't connect to a client, return false
        /// and close connection.
        /// Otherwise start listener and return true.
        /// </summary>
        /// <returns></returns>
        private async Task <bool> Connect()
        {
            if (!IsToServer)
            {
                Dispose();
                return(false);
            }

            var retries = 0;

            var failedToConnectException = new Exception();

            Client = new TcpClient();

            Client.ApplyConfig(config);

            while (!Client.Connected)
            {
                try
                {
                    await Client.ConnectAsync(Address.IPAddress, Address.Port);

                    if (Client.Connected)
                    {
                        StartListening();
                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    failedToConnectException = ex;
                }

                if (retries++ >= config.NumberOfRetries - 1)
                {
                    break;
                }

                logger.Warning($"Can't connect to {Address.IPAddress}:{Address.Port}." +
                               $" Will retry in {config.RetryDelay.Seconds} seconds. Retry: {retries}");

                await Task.Delay(config.RetryDelay, cancellationToken);
            }

            logger.Error("Error while connecting to the client", failedToConnectException);

            Dispose();

            return(false);
        }
Ejemplo n.º 2
0
        public ClientWrapper(
            TcpClient client,
            MeepoConfig config,
            CancellationToken cancellationToken,
            MessageReceivedHandler messageReceived,
            ClientConnectionFailed clientConnectionFailed)
            : this(config, cancellationToken, messageReceived, clientConnectionFailed)
        {
            IsToServer = false;

            Client = client;

            Client.ApplyConfig(config);

            Connected = true;

            StartListening();
        }