2

我已经搜索了如何实现简单的 ipv6 多播示例的示例,但是我只找到了使用 ipv4 的示例。

任何人都可以提供一个简单的“helloworld”ipv6 多播示例吗?

4

2 回答 2

7

这是一个简单的客户端服务器示例。顺便说一下,在网络上的多台机器上运行它会让所有机器互相聊天,这对测试网络上的自动发现很有好处。

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);
            }
        }
    });
}

}

希望有帮助。米

于 2013-11-18T23:20:32.780 回答
0

Java 中 IPv6 程序和 IPv4 程序之间的唯一区别是 IP 地址。在这种情况下,您必须在加入组和发送给组时使用 IPv6 样式的多播地址。其他一切都是一样的。

于 2013-11-19T01:17:25.930 回答