本文介绍了如何在NIO.2中实现多播客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用Java 7 NIO.2多播客户端的示例如何?我只能在文档。
How would an example of using a Java 7 NIO.2 multicast client look like? I could only find half of an example in the MulticastChannel documentation.
推荐答案
此示例有效。请注意 DatagramChannel.join()
需要 NetworkInterface
才能工作。
This example works. Note that DatagramChannel.join()
requires a NetworkInterface
to work.
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
}
}
这篇关于如何在NIO.2中实现多播客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!