自动重试连接

auto retry connection

我正在尝试使用 TCPCLIENT 通过 .NET 构建一个检查器

对于每封要检查的电子邮件,我的应用程序都在我的服务器和 smtp 服务器之间建立连接,这意味着有时 smtp 服务器不响应。

我要找的问题是如何不断重试连接 如果连接丢失。

这是我的代码:

TcpClient tClient = new TcpClient("smtp-in.orange.fr", 25);
string CRLF = "\r\n";
byte[] dataBuffer;

string ResponseString;
NetworkStream netStream = tClient.GetStream();
StreamReader reader = new StreamReader(netStream);
ResponseString = reader.ReadLine();

/* Perform HELO to SMTP Server and get Response */
dataBuffer = BytesFromString("HELO KirtanHere" + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
ResponseString = reader.ReadLine();
dataBuffer = BytesFromString("mail from:<contact@contact.com>" + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
ResponseString = reader.ReadLine();

看来您需要在 for 循环中实现 try catch 块。

for (var i = 0; i < retryCount; i++)
{
   try
   {
       YourAction();
       break; // success
   }
   catch { /*ignored*/ }

   // give a little breath..
   Thread.Sleep(50); 
}

看起来很丑但很简单,在某些情况下不推荐使用。你可能想试试 Polly,这个库允许你表达异常处理策略,包括重试。

我还想指出,您从未处理过 NetworkStreamStreamReader 等一次性物品。由于您 运行 漫长的 运行 过程,您 应该 处理它们。

private static void YourAction()
{
   var tClient = new TcpClient("smtp-in.orange.fr", 25);
   const string CRLF = "\r\n";

   string ResponseString;
   using (var netStream = tClient.GetStream())
   using (var reader = new StreamReader(netStream))
   {
       ResponseString = reader.ReadLine();

       /* Perform HELO to SMTP Server and get Response */
       var dataBuffer = BytesFromString("HELO KirtanHere" + CRLF);
       netStream.Write(dataBuffer, 0, dataBuffer.Length);
       ResponseString = reader.ReadLine();
       dataBuffer = BytesFromString("mail from:<contact@contact.com>" + CRLF);
       netStream.Write(dataBuffer, 0, dataBuffer.Length);
       ResponseString = reader.ReadLine();
    }
}

一种解决方案是使用 Polly 库。

使用 Polly,您需要配置 Policy,以便在哪些情况下重试。

请指定您的例外政策,如下所示

var maxRetryAttempts = 3;
var pauseBetweenFailures = TimeSpan.FromSeconds(2);

var retryPolicy = Policy
    .Handle<Exception>()// Handle specific exception
    .WaitAndRetryAsync(maxRetryAttempts, i => pauseBetweenFailures);

包围您的代码
await retryPolicy.ExecuteAsync(async () =>
{
TcpClient tClient = new TcpClient("smtp-in.orange.fr", 25);
string CRLF = "\r\n";
byte[] dataBuffer;
.....
});

关于如何使用 Polly 的详细说明,有很好的文章..

https://alastaircrabtree.com/implementing-the-retry-pattern-using-polly/