是否可以检测套接字是否处于 CLOSE_WAIT 状态? [英] Is it possible to detect if a socket is in the CLOSE_WAIT state?
问题描述
我正在使用 TcpClient
对象来发送和接收数据.当客户端失去连接时,我可以通过使用 TcpView 看到其关联的连接处于 CLOSE_WAIT
状态.是否可以在 C# 中查看套接字的状态?我只是想检测 CLOSE_WAIT
状态,以便我可以关闭服务器端的套接字.我知道我可以等待一段时间接收字节,然后在没有收到任何内容时关闭连接.我宁愿立即关闭套接字及其线程.是否可以在 c# 端检测到套接字的状态?TcpView 程序可以确定这一点.c# 程序可以做到这一点吗?
I am using a TcpClient
object to send and receive data. When a client loses its connection, I can see by using TcpView that its associated connection is in a CLOSE_WAIT
state. Is it possible in c# to see the state of a socket? I simply want to detect the CLOSE_WAIT
state so I can close the socket on the server end. I understand that I can wait to receive bytes for a certain amount of time and then close the connection if nothing is received. I just would rather close the socket and its thread immediately. Is the socket's state able to be detected on the c# side? The TcpView program can determine this. Can a c# program do this?
推荐答案
这并不理想,但如果您查看 socket.Available
,它会抛出一个SocketException
.不过,您仍然需要检查原因.
It's not ideal, but if you check socket.Available
, it'll throw a SocketException
. You still need to check the reason, though.
也不太理想,因为有点笨重,就是调用Poll()
(使用 SelectRead
).如果它返回 true
,要么有数据要读取,要么连接关闭.如果没有要读取的数据,那就是您的答案.
Also not ideal, because it's a bit clunky, is to call Poll()
(with SelectRead
). If it returns true
, either there's data to read or the connection is closed. If there's no data to read, then that's your answer.
这篇关于是否可以检测套接字是否处于 CLOSE_WAIT 状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!