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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With