简体   繁体   English

套接字setSoTimeout的说明

[英]Socket setSoTimeout clarification

I have scenario in which there is server listening on specified ip and port and client which connects to that server. 我有一种方案,其中有服务器在指定的IP和端口上侦听,并且有客户端连接到该服务器。 Now I am reading response from server using readline method: 现在,我正在使用readline方法从服务器读取响应:

String readme=bs.readline()).   

Here bs is bufferedreader object. 这里bsbufferedreader对象。 I want to know if before reading response if I write this line 我想知道在阅读回复之前是否写这行

socket.setSoTimeout(1000)

and if no response come till 1000 ms 如果没有响应,直到1000毫秒

whether socket get timeout and get disconnected or it do not disconnect socket and give empty string in readme . 套接字是否超时并断开连接,还是不断开套接字并在readme提供空字符串。

Actually neither. 实际上两者都不是。 A SocketTimeoutException is thrown. 抛出SocketTimeoutException

From the docs : 文档

setSoTimeout

 public void setSoTimeout(int timeout) throws SocketException 

Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. 以指定的超时时间启用/禁用SO_TIMEOUT,以毫秒为单位。 With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. 通过将此选项设置为非零超时,与此套接字关联的InputStream上的read()调用将仅在此时间量内阻塞。 If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. 如果超时到期,则尽管Socket仍然有效,但将引发java.net.SocketTimeoutException。 The option must be enabled prior to entering the blocking operation to have effect. 必须先启用该选项,然后才能执行阻止操作。 The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout. 超时必须大于0。零超时被解释为无限超时。

Parameters: timeout - the specified timeout, in milliseconds. 参数: timeout指定的超时(以毫秒为单位)。 Throws: SocketException - if there is an error in the underlying protocol, such as a TCP error. 抛出: SocketException如果基础协议中存在错误,例如TCP错误。

The socket will not disconnect. 插座不会断开。 Instead, any reading method will throw a SocketTimeoutException that you may wish to catch in your program. 相反,任何读取方法都将引发您可能希望在程序中捕获的SocketTimeoutException。 The socket can still be used, but readme in such a case will not be defined: 套接字仍然可以使用,但是在这种情况下将无法定义readme

String readme;
try
{
 readme = bs.readline;
// TODO do stuff with readme
}
catch (SocketTimeoutException e)
{
// did not receive the line. readme is undefined, but the socket can still be used
 socket.close(); // disconnect, for example
}

It is assumed in the example that IOException s are caught elsewhere or thrown. 在示例中假定IOException被捕获在其他地方或被抛出。

The docs explain this behaviour quite well: Socket.setSoTimeout(int) 该文档很好地解释了此行为: Socket.setSoTimeout(int)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM