This section describes how to bind a socket to a specific port. Binding multiple client sockets to the same port is not allowed.
As I mentioned previously, I used a special socket constructor to allow the system
to bind the socket an un-specified local address and port number. This gives the
system the freedom to pickup an un-used port number. If I change SocketClient.java
from:
Socket c = new Socket("localhost",8888);
to:
Socket c = new Socket();
c.bind(new InetSocketAddress("localhost",4444));
c.connect(new InetSocketAddress("localhost",8888));
the first running instance of SocketClient will work, but additional running
instances will get the following error:
java.net.BindException: Address already in use: JVM_Bind
Why? Because, at any given time, only one socket can be bound to a given port.
So, allowing the system to pick up a free local port number is a better idea.
However, the sockets created by the ServerSocket.accept() method seems to be
allowed to bind to the same local port. See the output of ReverseEchoServer.
When two or more client programs are connected to it, sockets created for
the connections are all bound to the same port number, 8888.
Exercise: Can you re-bind a bound socket to new port number?