IPv6组播示例 [英] IPv6 Multicast example
本文介绍了IPv6组播示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经搜索了如何实现简单ipv6组播示例的示例,但是我只找到了使用ipv4的示例。
I've searched for examples of how to implement a simple ipv6 multicast example, however I have only found examples using ipv4.
任何人都可以提供简单的helloworld ipv6多播的例子?
Can anybody provide a simple "helloworld" example of ipv6 multicasting?
推荐答案
这是一个简单的客户端服务器示例。顺便说一句,在网络上的多台机器上运行它会让所有机器互相聊天,这对于在网络上测试自动发现很有帮助。
Here is a simple client server example. Incidentally running it on multiple machines on a network wil get all the machines chatting to each other, good for testing automatic discovery on the network.
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);
}
}
});
}
}
希望有所帮助。
M
Hope that helps. M
这篇关于IPv6组播示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文