Who knows how the port is chosen when I’m using accept method of ServerSocket class? Is it possible to define a range for the ports the method can choose from? Can I ‘take’ ports one by one just in order?
ServerSocket sSocket = new ServerSocket(5050);
Socket socket = sSocket.accept();

The diagram is incorrect (and is listed in the unconfirmed errata on the O’Reilly site).
The client chooses its port at random (you don’t need to do anything special in Java) and connects to the server on whichever port you specified. Using the
netstatcommandline tool you can see this.First, just the listening server socket with no clients:
(there are lots of other entries, I’ve just removed the unrelated ones)
Now with one client connecting from localhost (127.0.0.1):
Since the client is connecting from the same machine, we see two established connections – one from client to server (1), the other from server to client (2). They have opposite local and foreign addresses (since they’re talking to each other) and you can see the server is still using port 5050 while the original server socket (3) continues to listen on the same port.
(this output is from a Mac, but Windows/Linux also have
netstatgiving similar output)