Exemple #1
0
        protected override void Arrange()
        {
            base.Arrange();

            _client = new MyClient(_connectionInfo, false, _serviceFactoryMock.Object);
            _client.Connect();
        }
Exemple #2
0
        public void ConnectTest()
        {
            BaseClient target = CreateBaseClient(); // TODO: Initialize to an appropriate value

            target.Connect();
            Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
        /// <summary>
        /// 重新连接方法
        /// </summary>
        internal void Reconnect()
        {
            string temp = string.Format("TCP主机地址:{0},端口号:{1}", ServerIp, ServerPort); //TCP连接的主机地址与端口

            LastErrorMessage = "TCP连接意外断开,正在尝试重连。" + temp;
            //FileClient.WriteFailureInfo(LastErrorMessage);
            try
            {
                BaseClient.Close();
                BaseClient = HoldLocalPort ? new TcpClient(LocalEndPoint) : new TcpClient();
                BaseClient.Connect(ServerIp, ServerPort);
                SetName();

                //重连次数+1,同时调用事件委托
                ReconnTimer++;
                if (ReconnTimerChanged != null)
                {
                    ReconnTimerChanged.BeginInvoke(Name, ReconnTimer, null, null);
                }

                NetStream = BaseClient.GetStream();
                if (AutoReceive)
                {
                    NetStream.BeginRead(Buffer, 0, Buffer.Length, new AsyncCallback(TcpCallBack), this);
                }
                //FileClient.WriteFailureInfo("TCP重新连接成功。" + temp);
            }
            //假如出现异常,将错误信息写入日志并进入下一次循环
            catch (Exception e)
            {
                LastErrorMessage = string.Format("TCP重新连接失败:{0}。", e.Message) + temp;
            }
        }
Exemple #4
0
        // attempt to connect x times to fix known issue with SSH library
        public static void ConnectWithRetry(BaseClient client, int attempts)
        {
            if (!client.IsConnected)
            {
                bool isAuthenticated = true;

                for (int i = 0; i < attempts && isAuthenticated && !client.IsConnected; i++)
                {
                    try{
                        client.Connect();
                    }
                    catch (Renci.SshNet.Common.SshAuthenticationException) {
                        isAuthenticated = false; // leave early so we don't lock out account from bad credentials
                    }
                    catch (Renci.SshNet.Common.SshConnectionException) {
                        // Fix bizarre error found with Renci.SshNet => Server response does not contain SSH protocol identification.
                        // https://stackoverflow.com/questions/54523798/randomly-getting-renci-sshnet-sftpclient-connect-throwing-sshconnectionexception
                        //
                        // This occurred frequently when connecting to PUB400.COM, really not sure why.
                    }
                }
                if (!isAuthenticated)
                {
                    throw new KanpachiAuthenticationException("Failed to authenticate with current credentials for " +
                                                              $"{client.ConnectionInfo.Username}@{client.ConnectionInfo.Host}.");
                }
                if (!client.IsConnected)
                {
                    throw new KanpachiConnectionException($"Failed to connect to {client.ConnectionInfo.Host} after {attempts} attempt(s).");
                }
            }
        }
        protected void Arrange()
        {
            _connectionInfo = new ConnectionInfo("host", "user", new PasswordAuthenticationMethod("user", "pwd"));
            _keepAliveSent  = new ManualResetEvent(false);

            _serviceFactoryMock = new Mock <IServiceFactory>(MockBehavior.Strict);
            _sessionMock        = new Mock <ISession>(MockBehavior.Strict);

            _mockSequence = new MockSequence();

            _serviceFactoryMock.InSequence(_mockSequence).Setup(p => p.CreateSession(_connectionInfo)).Returns(_sessionMock.Object);
            _sessionMock.InSequence(_mockSequence).Setup(p => p.Connect());
            _sessionMock.InSequence(_mockSequence).Setup(p => p.TrySendMessage(It.IsAny <IgnoreMessage>()))
            .Returns(true)
            .Callback(() =>
            {
                Thread.Sleep(300);
                _keepAliveSent.Set();
            });

            _client = new MyClient(_connectionInfo, false, _serviceFactoryMock.Object)
            {
                KeepAliveInterval = TimeSpan.FromMilliseconds(50d)
            };
            _client.Connect();
        }
        static void Main()
        {
            BaseClient client = new BaseClient();                                                            //Create an instance of the client used to connect to the server

            client.Connect("127.0.0.1", 6789);                                                               //Connect to the server using the ip and port provided
            while (client.IsConnected())                                                                     //While we are connected to the server
            {
                Packet p1 = new Packet(10);                                                                  //Create an empty packet of type 10
                p1.Add(DateTime.Now.Ticks);                                                                  //Add to the packet a long, in this case the current time in Ticks
                p1.Add(2.3f);                                                                                //Add a float
                p1.Add(new Byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }); //Add a float
                p1.AddList(new List <Double>()
                {
                    10.1, 10.2, 10.3, 10.4
                });
                p1.AddList(new List <Single>()
                {
                    10.1f, 10.2f, 10.3f, 10.4f
                });
                client.SendPacket(p1);             //Send the packet over the connection (packet auto disposes when sent)

                Packet p2 = new Packet(11);        //Create an empty packet of type 10
                p2.Add(true);                      //Add to the packet a bool
                p2.Add("test cake");               //Add to the packet a string
                p2.Add(Guid.NewGuid());            //Add to the packet a GUID
                client.SendPacket(p2);             //Send the packet over the connection (packet auto disposes when sent)

                Thread.Sleep(20);                  //Wait for 20 ms before repeating
            }
            client.Disconnect();
        }
Exemple #7
0
 private Task Connect(BaseClient client) =>
 Task.Run(async() =>
 {
     var i      = 0;
     var maxTry = 5;
     while (i < maxTry)
     {
         try
         {
             client.KeepAliveInterval = KeepAliveSpan;         // avoid client drops
             client.Connect();
             break;
         }
         catch (Exception ex)
         {
             Log.Error($"Connect to {client.ConnectionInfo.Host} error: {ex}");
             if (i == maxTry)
             {
                 throw;
             }
             else
             {
                 Log.Information($"retry connect to the client");
                 await Task.Delay(TimeSpan.FromSeconds(5));
             }
         }
         i++;
     }
 });
Exemple #8
0
 public void Connect(string host, int port)
 {
     if (Connected)
     {
         Disconnect();
     }
     BaseClient.Connect(host, port);
 }
Exemple #9
0
 /// <summary>
 /// Robustly make the connection to an ssh endpoint. This includes retries and the like.
 /// </summary>
 /// <param name="c"></param>
 private static void ConnectSSHRobustly(BaseClient c)
 {
     c.KeepAliveInterval = TimeSpan.FromSeconds(15);
     Policy
     .Handle <SshOperationTimeoutException>()
     .Or <SshConnectionException>()
     .WaitAndRetry(new[] { TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(60) }, (exception, timespan, count, ctx) => Trace.WriteLine($"Failed to connect to {c.ConnectionInfo.Host} ({exception.Message}) - retry count {count}"))
     .Execute(() => c.Connect());
 }
        protected void Arrange()
        {
            SetupData();
            CreateMocks();
            SetupMocks();

            _client = new MyClient(_connectionInfo, false, _serviceFactoryMock.Object);
            _client.Connect();
        }
Exemple #11
0
        /// <summary>
        /// UDP重新连接方法
        /// </summary>
        private void TcpAutoReconnect()
        {
            while (true)
            {
                Thread.Sleep(1000);

                //假如属性提示未连接,则UDP重连线程挂起
                if (!IsConnected)
                {
                    Auto_UdpReconnect.WaitOne();
                }
                //假如属性提示已连接但实际上连接已断开,尝试重连
                //else if (IsConnected && !IsSocketConnected())
                else if (IsConnected && !IsConnected_Socket)
                {
                    string temp = string.Format("UDP主机地址:{0},端口号:{1}", ServerIp, ServerPort); //UDP连接的主机地址与端口
                    LastErrorMessage = "UDP连接意外断开,正在尝试重连。" + temp;
                    FileClient.WriteFailureInfo(LastErrorMessage);
                    try
                    {
                        BaseClient.Close();
                        BaseClient = HoldLocalPort ? new UdpClient(LocalEndPoint) : new UdpClient();
                        BaseClient.Connect(ServerIp, ServerPort);
                        SetName();

                        //重连次数+1,同时调用事件委托
                        ReconnTimer++;
                        if (ReconnTimerChanged != null)
                        {
                            ReconnTimerChanged.BeginInvoke(Name, ReconnTimer, null, null);
                        }
                        if (Connected != null)
                        {
                            Connected.BeginInvoke(Name, new EventArgs(), null, null);
                        }

                        //NetStream = BaseClient.GetStream();
                        if (AutoReceive)
                        {
                            BaseClient.BeginReceive(new AsyncCallback(ReceiveCallBack), this);
                        }
                        //NetStream.BeginRead(Buffer, 0, Buffer.Length, new AsyncCallback(TcpCallBack), this);
                        //IsSocketConnected();
                        FileClient.WriteFailureInfo("UDP重新连接成功。" + temp);
                    }
                    //假如出现异常,将错误信息写入日志并进入下一次循环
                    catch (Exception e)
                    {
                        LastErrorMessage = string.Format("UDP重新连接失败:{0}。", e.Message) + temp;
                        FileClient.WriteExceptionInfo(e, LastErrorMessage, false);
                        continue;
                        //TODO: 是否抛出异常?
                        //throw; //假如不需要抛出异常,注释此句
                    }
                }
            }
        }
        protected override void Arrange()
        {
            base.Arrange();

            _client = new MyClient(_connectionInfo, false, _serviceFactoryMock.Object)
            {
                KeepAliveInterval = TimeSpan.FromMilliseconds(50d)
            };
            _client.Connect();
        }
Exemple #13
0
        protected void Arrange()
        {
            SetupData();
            CreateMocks();
            SetupMocks();

            _client = new MyClient(_connectionInfo, false, _serviceFactoryMock.Object)
            {
                KeepAliveInterval = TimeSpan.FromMilliseconds(50d)
            };
            _client.Connect();
        }
 /// <summary>
 /// constructor
 /// </summary>
 /// <param name="p_sftpcl">sftp client object</param>
 /// <param name="p_method">method, value: post or move</param>
 /// <param name="uriResponse"> uri to get response</param>
 /// <param name="p_InStream"> input stream, if is not null then upload, else download</param>
 public SftpWebResponse(BaseClient p_sftpcl, string p_method, Uri uriResponse, Uri uriMoveTo, Stream p_InStream)
 {
     m_uriResponse = uriResponse;
     m_method      = p_method;
     m_sftpClient  = p_sftpcl;
     if (!m_sftpClient.IsConnected)
     {
         m_sftpClient.Connect();
     }
     m_sReqStream = p_InStream;
     m_uriMoveTo  = uriMoveTo;
     m_whc.Add("ServerInfo", m_sftpClient.ConnectionInfo.ServerVersion.ToString());
     m_sResponse = doAction();
 }
Exemple #15
0
        private void tryConnect(string service, BaseClient client, bool terminateProcessOnException = false)
        {
            try
            {
                client.Connect();
            }
            catch (Exception ex)
            {
                bool gracefulFail = false;

                if (ex is SocketException)
                {
                    Logger.WriteLine(10, $"ERROR: During { service } startup a Socket connection could not be established! Check your host name/address, and that the host is running.");
                    gracefulFail = true;
                }
                else if (ex is SshConnectionException)
                {
                    Logger.WriteLine(10, $"ERROR: During { service } startup an SSH session could not be established! Check SSH is enabed on the server.");
                    gracefulFail = true;
                }
                else if (ex is SshAuthenticationException)
                {
                    Logger.WriteLine(10, $"ERROR: During { service } startup SSH authentication failed. Check your username and password!");
                    gracefulFail = true;
                }
                else if (ex is ProxyException)
                {
                    Logger.WriteLine(10, $"ERROR: During { service } startup a proxy connection could not be established!");
                    gracefulFail = true;
                }
                else if (ex is SshOperationTimeoutException)
                {
                    Logger.WriteLine(10, $"SSH During { service } startup the connection timed out!");
                    gracefulFail = true;
                }

                if (gracefulFail)
                {
                    _tcs.TrySetResult(false);
                    if (terminateProcessOnException)
                    {
                        Environment.Exit(1);
                    }
                }

                throw;
            }
        }
        protected void Arrange()
        {
            _connectionInfo = new ConnectionInfo("host", "user", new PasswordAuthenticationMethod("user", "pwd"));

            _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Strict);
            _sessionMock = new Mock<ISession>(MockBehavior.Strict);

            _serviceFactoryMock.Setup(p => p.CreateSession(_connectionInfo)).Returns(_sessionMock.Object);
            _sessionMock.Setup(p => p.Connect());
            _sessionMock.Setup(p => p.TrySendMessage(It.IsAny<IgnoreMessage>()))
                .Returns(true)
                .Callback(() => Thread.Sleep(300));

            _client = new MyClient(_connectionInfo, false, _serviceFactoryMock.Object)
                {
                    KeepAliveInterval = TimeSpan.FromMilliseconds(50d)
                };
            _client.Connect();
        }
Exemple #17
0
        public void Connect(string ip, int port)
        {
            if (String.IsNullOrEmpty(ip))
            {
                return;
            }
            var       IPs = Dns.GetHostAddresses(ip);
            IPAddress IP  = IPs.Where(x => x.AddressFamily == AddressFamily.InterNetwork).FirstOrDefault();
            var       ep  = new IPEndPoint(IP, port);

            try
            {
                BaseClient.Connect(ep);
            }
            catch
            {
                return;
            }
            ns = new NetworkStream(BaseClient);
            Thread thread = new Thread(o => ReceiveData((Socket)o));

            thread.Start(BaseClient);
        }
Exemple #18
0
        private void Connect(BaseClient client)
        {
            int retry = 10;

            while (retry-- > 0)
            {
                try
                {
                    client.Connect();
                    if (verboseMode)
                    {
                        ConsoleOutput($"- {client.GetType().Name} connected");
                    }
                    return;
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine($"Error connecting to server (retrying): {ex.Message}");
                    Thread.Sleep(2000);
                }
            }
            throw new AppException("Giving up connecting to server.");
        }
        /// <exception cref="NodeConnectionFailedException"></exception>
        private async Task CreateConnectionInner(BaseClient client, NodeCredentials conn, CancellationToken ct)
        {
            try
            {
                logger.LogDebug("Resolving host");
                await Dns.GetHostEntryAsync(conn.host);

                logger.LogDebug("Resolved");
            }
            catch (Exception ex)
            {
                logger.LogDebug("Host resolution failed");
                client.Dispose();
                throw new NodeConnectionFailedException(ex.Message, ex)
                      {
                          Kind = NodeConnectionFailedException.ConnectionErrorKind.DNS
                      };
            }

            try
            {
                logger.LogDebug("Connecting");
                client.Connect();
                logger.LogDebug("Connected");
            }
            catch (SshAuthenticationException ex)
            {
                logger.LogDebug("Connection failed because to authenticate {error}", ex.Message);
                client.Dispose();
                throw new NodeConnectionFailedException(ex.Message, ex)
                      {
                          Kind = NodeConnectionFailedException.ConnectionErrorKind.Authentication
                      };
            }
            catch (SshConnectionException ex)
            {
                logger.LogDebug("Connection failed due to SSH connection error {error}", ex.Message);
                client.Dispose();
                throw new NodeConnectionFailedException(ex.Message, ex)
                      {
                          Kind = NodeConnectionFailedException.ConnectionErrorKind.Connection
                      };
            }
            catch (SocketException ex)
            {
                logger.LogDebug("Connection failed due to socket exception {error}", ex.Message);
                client.Dispose();
                throw new NodeConnectionFailedException(ex.Message, ex)
                      {
                          Kind = NodeConnectionFailedException.ConnectionErrorKind.Connection
                      };
            }
            catch (TaskCanceledException)
            {
                logger.LogDebug("Connection cancelled");
                client.Dispose();
                throw;
            }
            catch (Exception ex)
            {
                logger.LogDebug("Connection failed for unknown reason {error}", ex.Message);
                client.Dispose();
                throw new NodeConnectionFailedException(ex.Message, ex)
                      {
                          Kind = NodeConnectionFailedException.ConnectionErrorKind.Unknown
                      };
            }
        }
Exemple #20
0
 public void Connect(string ip, ushort tcpPort) => BaseClient.Connect(ip, tcpPort);
        /// <summary>
        /// 利用特定的本地端口与TCP服务端连接
        /// </summary>
        /// <param name="server">TCP服务端IP</param>
        /// <param name="port">端口号</param>
        /// <param name="localIp">本地IP</param>
        /// <param name="localPort">指定的本地端口(假如小于等于0则随机)</param>
        /// <returns>假如建立连接成功,返回1,否则返回0</returns>
        public int Connect(string server, int port, string localIp, int localPort)
        {
            //尝试建立连接
            int result = 1;

            try
            {
                ServerIp   = server;
                ServerPort = port;
                //BaseClient = new TcpClient(ServerIp, ServerPort);
                BaseClient = !string.IsNullOrWhiteSpace(localIp) && localPort > 0 ? new TcpClient(new IPEndPoint(IPAddress.Parse(localIp), localPort)) : new TcpClient();
                BaseClient.Connect(ServerIp, ServerPort);
                SetName(); //修改连接名称

                //重置重连次数,同时调用事件委托
                ReconnTimer = 0;
                if (ReconnTimerChanged != null)
                {
                    ReconnTimerChanged.BeginInvoke(Name, ReconnTimer, null, null);
                }

                BaseClient.ReceiveBufferSize = ReceiveBufferSize; //接收缓冲区的大小
                NetStream = BaseClient.GetStream();               //发送与接收数据的数据流对象
                raiser.Run();
            }
            catch (Exception e)
            {
                LastErrorMessage = string.Format("无法建立TCP连接,IP{0},端口号{1}:{2}", ServerIp, ServerPort, e.Message);
                if (logging)
                {
                    FileClient.WriteExceptionInfo(e, LastErrorMessage, false);
                }
                Close();
                result = 0;
                throw; //假如不需要抛出异常,注释此行
            }

            IsConnected = BaseClient.Connected;
            IsSocketConnected();
            if (IsConnected)
            {
                //调用Tcp连接事件委托
                if (Connected != null)
                {
                    Connected.BeginInvoke(Name, (new EventArgs()), null, null);
                }
                if (Thread_TcpReconnect == null)
                {
                    Auto_TcpReconnect   = new AutoResetEvent(true);
                    Thread_TcpReconnect = new Thread(new ThreadStart(TcpAutoReconnect))
                    {
                        IsBackground = true
                    };
                    //Thread_TcpReconnect.IsBackground = true;
                    Thread_TcpReconnect.Start();
                }
                else
                {
                    Auto_TcpReconnect.Set();
                }
                if (AutoReceive)
                {
                    NetStream.BeginRead(Buffer, 0, Buffer.Length, new AsyncCallback(TcpCallBack), this);
                }
            }
            return(result);
        }