如果崩溃,请将 TcpClient 重新连接到服务器

Reconnect TcpClient to Server if it crashes

我正在尝试制作一个 Steam 喜欢的朋友客户端 ...

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


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();

       }

先谢谢了

包装任何操作,例如在 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();

        }