自动重试连接

时间:2018-11-04 14:31:55

标签: c# .net tcpclient

我正在尝试使用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();

2 个答案:

答案 0 :(得分:1)

似乎您需要在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();
    }
}

答案 1 :(得分:0)

一种解决方案是使用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/

相关问题