Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of an unbound socket?

Tags:

java

sockets

I am new to networking in Java and in general. I was reading up on sockets and saw the ServerSocket class had a constructor for an unbound socket.

I thought the way socket connections worked was by connecting to specific ports. How could an unbound ServerSocket ever be used then?

thanks.

like image 623
user2910237 Avatar asked Mar 16 '14 06:03

user2910237


1 Answers

An unbound ServerSocket cannot be used to accept connections before it is bound.

The no-argument constructor that doesn't yet bind the ServerSocket exists so that you can call other methods on the ServerSocket before binding it using the bind method. There's one method in particular that must be called before binding: setReuseAddress(boolean on). It's Javadoc mentions:

Enabling SO_REUSEADDR prior to binding the socket using {@link #bind(SocketAddress)} allows the socket to be bound even though a previous connection is in a timeout state.

(You could also say that the constructors that do perform a bind are merely convenience methods so that you don't have to call the method bind(SocketAddress) separately.)

like image 88
Erwin Bolwidt Avatar answered Sep 28 '22 00:09

Erwin Bolwidt