我在用C#编写的Windows服务中有一个TCP / IP客户端程序。截至目前一切正常。但我有一个查询,假设我的机器连接由于任何原因说机器不在网络或其他原因而关闭。我的应用程序将如何检测到它并尝试再次连接或重新获得连接?
以下是我在Windows服务中使用的代码:
private ManualResetEvent _shutdownEvent = new ManualResetEvent(false);
protected override void OnStart(string[] args)
{
_thread = new Thread(DoWork);
_thread.Start();
System.Timers.Timer _timer = new System.Timers.Timer(60 * 1000); // every 60 seconds
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
_timer.Start(); // <- important
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (client.Connected)
{
//Do nothing
}
else {
//close the thread and again start.
try
{
using (StreamWriter streamWriter = File.AppendText(textfileSaveLocation))
{
streamWriter.WriteLine("Disconnected!!!!");
}
}
catch (Exception Ex)
{
Ex.Message.ToString();
}
_shutdownEvent.Set();
_thread.Start();
}
}
private void DoWork()
{
while (!_shutdownEvent.WaitOne(0))
{
TcpClient client = new TcpClient();
string data= "";
fileSaveLocation = location;
try
{
client.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
}
catch (Exception ex)
{
// Log the error here.
client.Close();
continue;
}
try
{
using (NetworkStream stream = client.GetStream())
{
byte[] notify = Encoding.ASCII.GetBytes("Hello");
stream.Write(notify, 0, notify.Length);
byte[] data = new byte[1024];
while (!_shutdownEvent.WaitOne(0))
{
int numBytesRead = stream.Read(data, 0, data.Length);
if (numBytesRead > 0)
{
data= Encoding.ASCII.GetString(data, 0, numBytesRead);
}
}
}
}
catch (Exception ex)
{
// Log the error here.
client.Close();
}
}
}
protected override void OnStop()
{
_shutdownEvent.Set(); // trigger the thread to stop
_thread.Join(); // wait for thread to stop
}
请帮帮我。任何建议都会有所帮助。谢谢..
答案 0 :(得分:0)
TcpClient
不会收到通知。您可以手动检查TcpClient
是否在每个特定时期内连接,如 -
if(tcpClient.Connected)
{
//code
}
else
{
//renew connection
}
或者,您必须根据需要处理Catch块中的Exception
。