Thursday, October 29, 2009

Setting Java Socket Timeouts

Oddly, Java's Socket library doesn't allow you to set the socket timeout directly in the constructor. Its important to note that there is no default so the socket will last forever (ish).

Note: The socket timeouts below apply to different situations: setSoTimeout applies to read timeouts. connect applies to connection establishment. At least that's how I read it.

I found two options, setting the option on the socket after creating one simplest (for me at least):
Socket s;

try {
s = new Socket( ip, port );
s.setSoTimeout( secs * 1000 ); // converts secs to ms

// do other stuff like get input stream and read it
}
catch ( SocketException se ) {
// catch timeout or other socket related error
}
catch ( Exception e ) {
// any other exception
}
The other option is creating a Socket object without any parameters then calling the connect method with timeout.

Here is a rough prototype since it seemed like pain to me but I was curious about the code:
Socket s = new Socket;

try {
s.connect( new InetSocketAddress( ip, port ), secs * 1000 );
}
catch ( SocketExpection se ) {
}
...snip...
I would guess there a whole load of exceptions that you would want to catch for both forms.

Take Care

3 comments:

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training Core Java 8 Training in Chennai Core java 8 online training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete
  2. Java Training Institutes Java Training Institutes Java EE Training in Chennai Java EE Training in Chennai Java Spring Hibernate Training Institutes in Chennai J2EE Training Institutes in Chennai J2EE Training Institutes in Chennai Core Java Training Institutes in Chennai Core Java Training Institutes in Chennai

    ReplyDelete
  3. Java Online Training Java Online Training Java Online Training Java Online Training Java Online Training Java Online Training

    Hibernate Training Institutes in ChennaiHibernate Training Institutes in Chennai Hibernate Online Training Hibernate Online Training Hibernate Training in Chennai Hibernate Training in Chennai

    ReplyDelete