当前位置: 技术问答>java相关
用java如何实现超时的问题?
来源: 互联网 发布时间:2015-04-10
本文导语: 譬如,在网络编程中,服务端规定在一定的时间内没有数据接收和发送,就将其TCP连接关闭;在客户端方,在一定的时间内没有数据接收,也将其TCP连接关闭。用java如何去做? | setSoTimeout publ...
譬如,在网络编程中,服务端规定在一定的时间内没有数据接收和发送,就将其TCP连接关闭;在客户端方,在一定的时间内没有数据接收,也将其TCP连接关闭。用java如何去做?
|
setSoTimeout
public void setSoTimeout(int timeout)
throws SocketException
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. 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. If the timeout expires, a java.io.InterruptedIOException is raised, though the Socket is still valid. 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.
public void setSoTimeout(int timeout)
throws SocketException
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. 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. If the timeout expires, a java.io.InterruptedIOException is raised, though the Socket is still valid. 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.
|
就socket连接来说,Socket和ServerSocket都有setSoTimeout方法,可以设超时。
|
可以用定时器来实现,这样CPU多了层开消。如果想在超时后进行相应处理,你可以捕捉超时异常来实现。
|
用TimerTask来实现定时器。