TCP 连接尝试超时
在 C# 中,我尝试测试与这样的端口的连接:
Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
socket.Connect(telco.Address, telco.Port);
当端口可用时,它工作得很好。然而,当端口不可用时(例如 TCP/81 上的 google.com),需要很长时间(约 60 秒)才会超时。这是一个状态页面,所以我想相对快速地失败。
我尝试将 socket.SendTimeout 和 socket.RecieveTimeout 设置为 5000ms(5 秒),但这似乎没有效果。
In C# I'm trying to test connectivity to a port like this:
Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
socket.Connect(telco.Address, telco.Port);
It works great when the port is available. However when the port is not available (e.g. google.com on TCP/81) it takes a long time (~60 seconds) for it to timeout. This is for a status page so I want to fail relatively quickly.
I tried to set socket.SendTimeout and socket.RecieveTimeout to 5000ms (5 seconds) but that appears to have no effect.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了保持简单性,我最终使用了与此类似的代码:
I ended up going with code similar to this to maintain simplicity:
认为您正在寻找 socket.ReceiveTimeout();
或使用 beginConnect() 并使用同步工具(例如 AutoResetEvent)来捕获超时。
请参阅这篇文章:如何配置套接字连接超时
think you're looking for socket.ReceiveTimeout();
or use beginConnect() and use a sync tool such AutoResetEvent to catch the time out.
see this post: How to configure socket connect timeout
要精细控制超时,请执行以下操作:
Application.DoEvents( )
Thread.Sleep()
以获得所需的超时间隔,或者使用其他方法来检查连接是的,您会在尝试连接的线程中收到异常。 并假设一切正常。
您可以放心地阅读它 rel="nofollow">http://msdn.microsoft.com/en-us/library/wahsac9k(v=VS.80).aspx
Socket.Close()
To fine control your timeout, do this:
Application.DoEvents()
Thread.Sleep()
for desired timeout interval. Or use some other method to make the time passSocket.Close()
on your waiting socket to break the connection attempt.Yes, you'll get the exception in the thread that tries to connect, but you can safely gobble it and assume that everything is OK.
http://msdn.microsoft.com/en-us/library/wahsac9k(v=VS.80).aspx
Socket.Close()