java - Setting a timeout for socket operations -
when create socket:
socket socket = new socket(ipaddress, port);
it throws exception, ok, because ip address not available. (the test variables string ipaddress = "192.168.0.3"
, int port = 300
.)
the problem is: how set timeout socket?
when create socket, how reduce time before unknownhostexception
, socket timeout?
use socket()
constructor, , connect(socketaddress endpoint, int timeout)
method instead.
in case like:
socket socket = new socket(); socket.connect(new inetsocketaddress(ipaddress, port), 1000);
quoting documentation
connect
public void connect(socketaddress endpoint, int timeout) throws ioexception
connects socket server specified timeout value. timeout of 0 interpreted infinite timeout. connection block until established or error occurs.
parameters:
endpoint
- socketaddress
timeout
- timeout value used in milliseconds.throws:
ioexception
- if error occurs during connection
sockettimeoutexception
- if timeout expires before connecting
illegalblockingmodeexception
- if socket has associated channel, , channel in non-blocking mode
illegalargumentexception
- if endpoint null or socketaddress subclass not supported socketsince: 1.4
Comments
Post a Comment