我已经搜索了如何实现简单ipv6组播示例的示例,但是我只找到了使用ipv4的示例。
任何人都可以提供一个简单的“helloworld”ipv6组播示例吗?
答案 0 :(得分:4)
这是一个简单的客户端服务器示例。顺便说一下,在网络上的多台机器上运行它会让所有机器互相聊天,这对于测试网络上的自动发现非常有用。
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UdpBroadcaster {
private static final Logger LOGGER = LoggerFactory.getLogger(UdpBroadcaster.class);
private static final int PORT = 9876;
private static final String MCAST_ADDR = "FF7E:230::1234";
private static InetAddress GROUP;
public static void main(String[] args) {
try {
GROUP = InetAddress.getByName(MCAST_ADDR);
Thread server = server();
server.start();
Thread.sleep(3000);
Thread client = client();
client.start();
client.join();
} catch (Exception e) {
LOGGER.error("Usage : [group-ip] [port]");
}
}
private static Thread client() {
return new Thread(new Runnable() {
public void run() {
MulticastSocket multicastSocket = null;
try {
multicastSocket = new MulticastSocket(PORT);
multicastSocket.joinGroup(GROUP);
while (true) {
try {
byte[] receiveData = new byte[256];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
multicastSocket.receive(receivePacket);
LOGGER.info("Client received from : " + receivePacket.getAddress() + ", " + new String(receivePacket.getData()));
} catch (Exception e) {
LOGGER.error(null, e);
}
}
} catch (Exception e) {
LOGGER.error(null, e);
} finally {
multicastSocket.close();
}
}
});
}
private static Thread server() {
return new Thread(new Runnable() {
public void run() {
DatagramSocket serverSocket = null;
try {
serverSocket = new DatagramSocket();
try {
while (true) {
byte[] sendData = new byte[256];
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, GROUP, PORT);
serverSocket.send(sendPacket);
ThreadUtilities.sleep(1000);
}
} catch (Exception e) {
LOGGER.error(null, e);
}
} catch (Exception e) {
LOGGER.error(null, e);
}
}
});
}
}
希望有所帮助。 中号
答案 1 :(得分:0)
IPv6程序和Java中的IPv4程序之间的唯一区别是IP地址。在这种情况下,您必须在加入组时以及向组发送时使用IPv6样式的多播地址。其他一切都是一样的。