配置Java Socket以在断开连接时快速失败? [英] Configure a Java Socket to fail-fast on disconnect?
问题描述
我的服务器上有一个监听端口,我正在使用Java类和 Socket
接口连接,即
I have a listening port on my server that I'm connecting to using a Java class and the Socket
interface, i.e.
Socket mySocket = new Socket(host,port);
然后我抓住 OutputStream
,装饰一个 PrintWriter
在autoflush模式下,我笑了 - 除非监听端口关闭。然后我得到
I then grab an OutputStream
, decorate with a PrintWriter
in autoflush mode and I'm laughing - except if the listening port closes. Then I get
tcp4 0 0 *.9999 *.* LISTEN
tcp 0 0 127.0.0.1.45737 127.0.0.1.9999 CLOSE_WAIT
我似乎无法在程序中发现问题 - 我我尝试在套接字上使用 isConnected()
方法但它似乎不知道连接已关闭。
and I can't seem to detect the problem in the program - I've tried using the isConnected()
method on the socket but it doesn't seem to know that the connection is closed.
我想在下次尝试写入Socket时意识到这个问题,以便我可以尝试重新连接并报告问题。
I want to be aware of the problem the next time I try and write to the Socket so that I can try and reconnect and report the issue.
任何建议拜托?
全部谢谢
推荐答案
设置短暂超时?
isOutputShutdown()
不能得到你想要的东西吗?
Does isOutputShutdown()
not get you what you want?
你总是可以构建一个 SocketWatcher
类,它在自己的 Thread
中旋转并反复尝试写空字符串到 Socket
,直到提升为止a SocketClosedException
。
You could always build a SocketWatcher
class that spins up in its own Thread
and repeatedly tries to write empty strings to the Socket
until that raises a SocketClosedException
.
这篇关于配置Java Socket以在断开连接时快速失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!