简体   繁体   中英

How does Java NIO constructs - socketchannel and socketserverchannel work internally?

I have some specific questions related to how socketchannel and socketserverchannel work:-

  1. 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();

  2. 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.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM