使用Java7NIO.2多播客户端的示例会是什么样的呢?我只能在MulticastChannel文档中找到一半的例子。
发布于 2014-02-20 12:37:53
这个例子很有效。注意,DatagramChannel.join()需要一个NetworkInterface才能工作。
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
InetAddress group = InetAddress.getByName("239.255.0.1")
DatagramChannel dc = DatagramChannel.open(StandardProtocolFamily.INET)
.setOption(StandardSocketOptions.SO_REUSEADDR, true)
.bind(new InetSocketAddress(5000))
.setOption(StandardSocketOptions.IP_MULTICAST_IF, ni);
MembershipKey key = dc.join(group, ni);
ByteBuffer byteBuffer = ByteBuffer.allocate(1500);
while (true) {
if (key.isValid()) {
byteBuffer.clear();
InetSocketAddress sa = (InetSocketAddress) dc.receive(byteBuffer);
byteBuffer.flip();
System.out.println("Multicast received from " + sa.getHostString());
// TODO: Parse message
}
}https://stackoverflow.com/questions/21908053
复制相似问题