示例#1
0
        private void StartAutoReconnect()
        {
            if (_IsDisposed)
            {
                return;
            }

            Timers.Create("AutoReconnect", _AutoReconnectTime, false, () =>
            {
                if (_IsConnected)
                {
                    return;
                }

                // if somehow autoreconnect called under _Client.Connected
                if (_Client.Connected)
                {
                    _Client.Close();
                    _IsInitialized = false;
                }

                if (!_IsInitialized)
                {
                    try
                    {
                        _Client = new TcpClient(_IPAddress.ToString(), _Port)
                        {
                            SendTimeout    = TcpSettings.SendTimeout,
                            ReceiveTimeout = TcpSettings.ReceiveTimeout
                        };

                        _NetworkStream = _Client.GetStream();
                        _Token         = _TokenSource.Token;

                        TcpSettings.TcpClient = _Client;

                        _IsInitialized = true;

                        StartWithoutChecks();
                    }
                    catch (Exception ex)
                    {
                        Events.HandleClientLog(this, new ClientLoggerEventArgs(LogType.EXCEPTION, "Can't reconnect to server...", ex));
                        StartAutoReconnect();
                    }
                }
                else
                {
                    try
                    {
                        if (_Client == null)
                        {
                            _IsInitialized = false;
                            return;
                        }

                        _Client.Connect(_IPAddress, _Port);

                        if (_Client.Connected)
                        {
                            _NetworkStream = _Client.GetStream();

                            StartWithoutChecks();
                        }
                    }
                    catch (Exception ex)
                    {
                        Events.HandleClientLog(this, new ClientLoggerEventArgs(LogType.EXCEPTION, "Can't reconnect to server...", ex));
                        StartAutoReconnect();
                    }
                }
            });
        }