gosr
gosr

Reputation: 4708

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?

Upvotes: 0

Views: 346

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

try

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

Upvotes: 2

PeterMmm
PeterMmm

Reputation: 24630

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);

Upvotes: 2

Related Questions