【问题标题】:Reconnect TcpClient to Server if it crashes如果 TcpClient 崩溃,请重新连接到服务器
【发布时间】:2023-03-09 19:58:01
【问题描述】:

我正在尝试制作一个 Steam Like Friends Client ...

我可以连接服务器,但是如果服务器崩溃,我该如何重新连接 .. . 并继续重新连接,直到服务器重新启动...


public void ConnectToUserServer()
       {
           lb_ConnectStatus.Text = "Connecting ... ";
           lb_ClientInfo.Text = "";

           byte[] sendBytes = new byte[10025];

           UserName = tb_UserName.Text;

           //Create an instance of TcpClient. 
           IPEndPoint ipend = new IPEndPoint(IPAddress.Parse(serverName), UsersPort);


           tcpClient.Connect(ipend);

           lb_ConnectStatus.Text = "Connected ... ";
           string HostName = Dns.GetHostName().ToString();

           IPAddress[] IpInHostAddress = Dns.GetHostAddresses(HostName);

           string IPV4Address = IpInHostAddress[2].ToString(); //Default IPV4Address.


           // LocalEndPoint will return the ip address and port to which the tcp connection is accepted
           var clientIpLAN = tcpClient.Client.LocalEndPoint;

           lb_ClientInfo.Text = HostName + " " + IPV4Address;

           networkStream = tcpClient.GetStream();
           send = UserName + " : " + IPV4Address;

           sendBytes = Encoding.ASCII.GetBytes(send);
           networkStream.Write(sendBytes, 0, sendBytes.Length);

           t = new Thread(DoWork);
           t.IsBackground = true;
           t.Start();

       }

从服务器接收用户列表


       public void DoWork()
       {

           byte[] bytes = new byte[1024];

           while (true)  
           { 
             int  bytesRead = networkStream.Read(bytes, 0, bytes.Length);

           }
           tcpClient.Close();
           ConnectToUserServer();

       }

先谢过

【问题讨论】:

  • 重连和第一次连不一样吗?
  • 当服务器关闭时,客户端崩溃,正在尝试重新连接,直到服务器再次启动...
  • 哦,你的意思是你想继续尝试重新连接?我想:尝试重新连接 -> 失败 -> 暂停 -> 重复直到连接成功。

标签: c# tcpclient reconnect


【解决方案1】:

Try .. Catch .. 中封装任何操作,例如读取或写入,并捕获任何错误。 然后在你的捕获中你尝试重新连接。如果重新连接成功,请在尝试中重新启动操作。如果不是,则重新抛出错误并最终停止。或者永远重试。

.net 中还有一个很受欢迎的库,Polly

// Retry once
Policy
  .Handle<SomeExceptionType>()
  .Retry()

// Retry multiple times
Policy
  .Handle<SomeExceptionType>()
  .Retry(3)

// Retry multiple times, calling an action on each retry 
// with the current exception and retry count
Policy
    .Handle<SomeExceptionType>()
    .Retry(3, onRetry: (exception, retryCount) =>
    {
        // Add logic to be executed before each retry, such as logging
    });

在你的情况下,是这样的:

        public void DoWork()
        {

            byte[] bytes = new byte[1024];

            int bytesRead;
            while (true)
                try
                {
                    bytesRead = networkStream.Read(bytes, 0, bytes.Length);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Could not get data from network stream, trying to reconnect. " + e.Message);

                    tcpClient.Reconnect(); // Do your reconnect here.

                    if (!tcpClient.isConnected)
                    {
                        Console.WriteLine("Could not reconnect, rethrowing error");
                        throw e;
                    }

                }


            tcpClient.Close();
            ConnectToUserServer();

        }

【讨论】:

    猜你喜欢
    • 2015-06-27
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    相关资源
    最近更新 更多