问题描述
我有一些关于 socketchannel 和 socketserverchannel 如何工作的具体问题:-
-
当 ServerSocketChannel 接受连接时(请参阅下面的代码),我的理解是它以某种方式将客户端移动到一个新的随机选择的端口。这样对吗?有没有办法从范围中选择这个端口?我问是因为当我编写这样的服务器并将其部署到 VM 时,我希望能够仅将一组端口列入白名单。如果可以通过 accept() 调用选择任何随机端口,我该如何实现?难道我不需要打开所有端口吗?
ServerSocketChannel socket = ServerSocketChannel.open();
socket.bind(new InetSocketAddress("localhost",1111));
... ..
SocketChannel AcceptedSocket= socket.accept();
-
客户端代码非常简单(请参考下面的代码)。
SocketChannel client= SocketChannel.open(new InetSocketAddress("localhost",1111)); .....//初始化缓冲区
client.write(buffer);
现在这个客户端正在尝试连接到端口 1111。客户端如何确定它被重定向到哪个端口?它怎么知道写操作必须发生在服务器选择的不同端口上?