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();
What does the ServerSocket method accept () return? Upon accepting a connection request from a TCP based client, the accept() method called on the server socket returns a socket that is connected to the client. Data can be sent and received using the socket returned by the accept() method.
The accept() call is used by a server to accept a connection request from a client. When a connection is available, the socket created is ready for use to read data from the process that requested the connection. The call accepts the first connection on its queue of pending connections for the given socket socket.
The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to the server on the given port. After the server is waiting, a client instantiates a Socket object, specifying the server name and the port number to connect to.
The ServerSocketChannel. accept method blocks and returns a SocketChannel object when a connection is accepted. The ServerSocket. read method blocks until input data are available, or a client is disconnected.
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 netstat
commandline tool you can see this.
First, just the listening server socket with no clients:
simon@lucifer:~$ netstat -n -a Active Internet connections (including servers) Proto Recv-Q Send-Q Local Address Foreign Address (state) ... tcp46 0 0 *.5050 *.* LISTEN ...
(there are lots of other entries, I've just removed the unrelated ones)
Now with one client connecting from localhost (127.0.0.1):
simon@lucifer:~$ netstat -n -a Active Internet connections (including servers) Proto Recv-Q Send-Q Local Address Foreign Address (state) ... tcp4 0 0 127.0.0.1.64895 127.0.0.1.5050 ESTABLISHED <- 1 tcp4 0 0 127.0.0.1.5050 127.0.0.1.64895 ESTABLISHED <- 2 tcp46 0 0 *.5050 *.* LISTEN <- 3 ...
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 netstat
giving similar output)
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