I'm trying to build a checker via .NET using TCPCLIENT
For each email to check my app is making a connection between my server and the smtp server which means sometimes the smtp server dont response.
The question that im looking for is how to keep retrying to connect if the connection missed .
Here is my code :
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();
Seems you need to implement try catch block inside for loop.
for (var i = 0; i < retryCount; i++)
{
try
{
YourAction();
break; // success
}
catch { /*ignored*/ }
// give a little breath..
Thread.Sleep(50);
}
Looks ugly but pretty simple, and for some cases it is not recommended. You may want to try Polly, this library allows you to express exception handling policies including Retry.
And also I want to point out that you've had never dispose disposable objects such as NetworkStream
and StreamReader
. Since you will run long running process, you should dispose them.
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();
}
}