I have some specific questions related to how socketchannel and socketserverchannel work:-
When a ServerSocketChannel accepts a connection( please refer to code below), my understanding is it somehow moves the client to a new randomly selected port. Is this correct? Is there a way to select this port from a range? I'm asking because when I write and deploy such a server to a VM, I want to be able to whitelist only a set of ports. If any random port can be selected by the accept() call, how can I achieve this? Wouldn't I have to open up all the ports?
ServerSocketChannel socket = ServerSocketChannel.open();
socket.bind(new InetSocketAddress("localhost", 1111));
... ..
SocketChannel acceptedSocket= socket.accept();
The client code is pretty simple( please refer to code below).
SocketChannel client= SocketChannel.open(new InetSocketAddress("localhost", 1111)); .....//initialize a buffer
client.write(buffer);
Now this client is trying to connect to port 1111. How does the client determine which is the port it has been redirected to? How does it know that the write operation must happen on a different port selected by the server?
It turns out I had understood wrong. When a connection is accepted, a new port is not created, instead a new socket descriptor is created for the same port. A different socket descriptor is created on the server for each client, and all interaction with that client is through that descriptor. This allows server to handle multiple clients in parallel.