客户端断开连接时如何检测关闭的TCP连接? [英] How to detect closed TCP connection when client disconnected disgracfully ?
本文介绍了客户端断开连接时如何检测关闭的TCP连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
How to detect closed TCP connection when Client disconnected disgracfully i.e sudden power off ?
以下方法当客户断断续续地断开连接时工作。
我尝试过:
Following method don't work when client disconnects disgracefully.
What I have tried:
<pre>if (socket != null)
{
bool part1 = socket.Poll(1000, SelectMode.SelectRead);
bool part2 = (socket.Available == 0);
if (part1 && part2)
{
return false;
}
else
{
return true;
}
}
else
return false;
推荐答案
TCP keepalive
这些看起来很有希望,在 .net中回答3 - 即时检测客户端断开服务器套接字 - 堆栈溢出 [ ^ ]
以及此处: http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html [ ^ ]
我希望它有所帮助。
TCP keepalive
These looks promising, answer 3 in .net - Instantly detect client disconnection from server socket - Stack Overflow[^]
and also here: http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html[^]
I hope it helps.
我使用过这样的东西:
I used something like this:
bool connectedLocal = true;
using (var socketTemp = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socketTemp.Connect(ip, port);
// Loop until prg finished or connection is lost.
while (Running && connectedLocal)
{
Thread.CurrentThread.Join(100);
connectedLocal = !(socketTemp.Poll(0, SelectMode.SelectRead) && socketTemp.Available == 0);
}
socketTemp.Close();
}
这篇关于客户端断开连接时如何检测关闭的TCP连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文