【发布时间】:2015-07-07 23:14:14
【问题描述】:
我正在编写一些使用 NIO 的客户端代码来侦听来自多个服务器的 UDP 数据包(其中许多被配置为回复同一个端口)。我尝试为每个已知服务器 NIO. 2 clients binding to same port, only 1 can read 设置专用频道失败了。
所以我现在尝试绑定到端口而不指定目的地
DatagramChannel channel = DatagramChannel.open();
channel.configureBlocking(false);
channel.socket().bind(new InetSocketAddress(port));
我的选择器现在成功接收到从我的所有服务器定向到此端口的所有 UDP 数据包
...
SelectionKey selKey = it.next();
if (selKey.isValid() && selKey.isReadable()) {
DatagramChannel sChannel = (DatagramChannel) selKey.channel();
sChannel.getRemoteAddress();//My problem lies here
....
正如预期的那样,sChannel.getRemoteAddress() 返回 null,因为我没有配置它。那么如何确定这个数据包的来源呢?
【问题讨论】: