DatagramSocket socket = vertx.createDatagramSocket(new DatagramSocketOptions());
socket.listen(1234, "0.0.0.0", asyncResult -> {
if (asyncResult.succeeded()) {
socket.handler(packet -> {
// Do something with the packet
});
// join the multicast group
socket.listenMulticastGroup("230.0.0.1", asyncResult2 -> {
System.out.println("Listen succeeded? " + asyncResult2.succeeded());
});
} else {
System.out.println("Listen failed" + asyncResult.cause());
}
});
执行后,我得到以下异常:
java.lang.NullPointerException: networkInterface
at io.netty.channel.socket.nio.NioDatagramChannel.joinGroup(NioDatagramChannel.java:409)
at io.netty.channel.socket.nio.NioDatagramChannel.joinGroup(NioDatagramChannel.java:368)
at io.netty.channel.socket.nio.NioDatagramChannel.joinGroup(NioDatagramChannel.java:362)
at io.vertx.core.datagram.impl.DatagramSocketImpl.listenMulticastGroup(DatagramSocketImpl.java:90)
我可以在提供网络接口的正确IP地址(例如192.168.178.52)而不是0.0.0.0时使用它。但是,这意味着遍历所有网络接口并为每个接口添加套接字。
有什么想法吗?谢谢!
答案 0 :(得分:1)
UDP多播侦听非常容易出错,尤其是在虚拟机中。
这是我的生产代码。首先,获得有效的界面:
static NetworkInterface mainInterface() throws SocketException {
final ArrayList<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
final NetworkInterface networkInterface = interfaces.stream().filter(ni -> {
boolean isLoopback = false;
boolean supportsMulticast = false;
boolean isVirtualbox = false;
try {
isLoopback = ni.isLoopback();
supportsMulticast = ni.supportsMulticast();
isVirtualbox = ni.getDisplayName().contains("VirtualBox") || ni.getDisplayName().contains("Host-Only");
} catch (IOException loopbackTestFailure) {
}
final boolean hasIPv4 = ni.getInterfaceAddresses().stream().anyMatch(ia -> ia.getAddress() instanceof Inet4Address);
return supportsMulticast && !isLoopback && !ni.isVirtual() && hasIPv4 && !isVirtualbox;
}).sorted(Comparator.comparing(NetworkInterface::getName)).findFirst().orElse(null);
return networkInterface;
}
然后,创建最防弹的数据报套接字:
String multicastAddress = "230.0.0.1";
NetworkInterface networkInterface = mainInterface();
Future isListening = Future.future();
vertx.createDatagramSocket(new DatagramSocketOptions()
.setReuseAddress(true)
.setReusePort(true))
.listen(6112, "0.0.0.0", next -> {
next.result().listenMulticastGroup(multicastAddress, networkInterface.getName(), null, listener -> {
final DatagramSocket socket = listener.result();
socket.handler(packet -> {
// Your handler here
});
isListening.complete();
});
});
观察我选择的高于1024的端口,重用标志和VirtualBox的特殊外壳。