如何设置套接字超时失败连接
问题描述:
我试图连接到套接字socket = new Socket(server , port);
,但如果服务器不可用,我需要设置失败连接超时。 默认超时时间为3min,例如,如果我开始连接11:50:22,错误将仅存在于11:53:31。查看日志:如何设置套接字超时失败连接
12-03 11:50:22.519: E/InternetIntentService(23897): Start connecting to localhost:9999
12-03 11:53:31.869: W/System.err(23897): java.net.ConnectException: failed to connect to /localhost (port 9999): connect failed: ETIMEDOUT (Connection timed out)
如何改变这种3分钟到10秒?
答
创建一个无参数的构造函数Socket
,然后调用connect(endpoint, timeout);
:
Socket s = new Socket();
s.connect(endpoint, timeout);
注意,相反的Javadoc,零并不意味着无穷大,这意味着平台默认(1分钟左右),并且您只能使用此技术来减少平台默认值,而不是增加平台默认值。