java * Windows 10,版本1703 * over * lo上的Java多播消息示例(软件环回接口1)*
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java * Windows 10,版本1703 * over * lo上的Java多播消息示例(软件环回接口1)*相关的知识,希望对你有一定的参考价值。
# out
---
```
is up: true
support multicast: true
is loopback: true
is point 2 point: false
java.net.SocketException: Network is unreachable: Datagram send failed
at java.net.TwoStacksPlainDatagramSocketImpl.send(Native Method)
at java.net.DatagramSocket.send(DatagramSocket.java:693)
at de.dailab.jiactng.MulticastExample.main(MulticastExample.java:42)
```
----
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.Optional;
import static java.lang.String.format;
public class MulticastExample {
public static void main(String[] args) {
MulticastSocket socket = null;
String address = "226.6.6.7";
int multicastPort = 9999;
InetAddress group = null;
Enumeration<NetworkInterface> networkInterfaces = null;
Optional<NetworkInterface> optLoInterface = Optional.empty();
try {
group = InetAddress.getByName(address);
socket = new MulticastSocket(multicastPort);
socket.setTimeToLive(1);
networkInterfaces = NetworkInterface.getNetworkInterfaces();
socket.joinGroup(group);
if (networkInterfaces.hasMoreElements()) {
optLoInterface = Collections.list(networkInterfaces).stream().filter(ni -> ni.getName().equals("lo")).findFirst();
}
if (optLoInterface.isPresent()) {
final NetworkInterface lo = optLoInterface.get();
System.out.println(format("is up: %b", lo.isUp()));
System.out.println(format("support multicast: %b", lo.supportsMulticast()));
System.out.println(format("is loopback: %b", lo.isLoopback()));
System.out.println(format("is point 2 point: %b", lo.isPointToPoint()));
socket.setNetworkInterface(lo);
byte[] buffer = new Date().toString().getBytes(StandardCharsets.UTF_8);
final DatagramPacket dp = new DatagramPacket(buffer, buffer.length, group, multicastPort);
socket.send(dp);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
以上是关于java * Windows 10,版本1703 * over * lo上的Java多播消息示例(软件环回接口1)*的主要内容,如果未能解决你的问题,请参考以下文章