简体   繁体   中英

Set timeout on Socket before it tries to connect

The Socket class documentation is here .

In my code atm, I use a constructor that's like this:

Socket m_Socket = new Socket(m_Address, m_Port);

m_Address is an InetAddress and m_Port is an int.

When this line runs, and the socket cannot be made, the app waits 3 seconds or so before throwing an IOException.

I can see there is no constructor that takes both InetAddress , int , and another int for timeout. I need to wait 250ms and not ~3 seconds as it is now. This means that I need to set the timeout on the socket, but I cannot find any method to do this. I know we have the method setSoTimeout(timeout) , but it needs to be called on an instance of the Socket class. I can instantiate a new Socket by doing this: m_Socket = new Socket(); , but then I'd need to set the InetAddress and port, and the Socket class does not seem to have any methods for doing this (except for the constructor).

How do I set the timeout before it actually tries to set the socket?

You may create an unconnected Socket with the default constructor and then call connect() with timeout.

Socket m_Socket = new Socket();
m_Socket.connect(addr,1000);

try

    Socket sock  = new Socket();
    sock.connect(new InetSocketAddress(m_Address, m_Port), 250);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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