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?