/* * Java読書会 ハンズオン * IPv6マルチキャスト実習 */ package javareading.handson.ipv6udp; import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; /** * マルチキャスト受信クラス。 * 「IPv6のマルチキャストソケット(UDP)を使って受信した内容と送信元を画面に出力する。 * * @author imai * */ public class MyMulticastReceiver implements Runnable { private static final int DATASIZE = 512; private static final int TIMEOUT = 15 * 1000; // msec private InetAddress mcastAddress; private MulticastSocket socket; private byte[] data; public MyMulticastReceiver(String host, int port) throws IOException { mcastAddress = InetAddress.getByName(host); socket = new MulticastSocket(port); socket.joinGroup(mcastAddress); socket.setSoTimeout(TIMEOUT); data = new byte[DATASIZE]; System.out.println("interface = " + socket.getInterface()); } public void run() { try { while (true) { DatagramPacket packet = new DatagramPacket(data, data.length); socket.receive(packet); System.out.println(new String(data, 0, packet.getLength()) + " from " + packet.getAddress() + ":" + packet.getPort()); } } catch (IOException e) { e.printStackTrace(); } finally { try { socket.leaveGroup(mcastAddress); } catch (IOException e) { e.printStackTrace(); } socket.close(); System.out.println("exiting"); } } public static void main(String args[]) throws IOException { new Thread(new MyMulticastReceiver("ff35:40:fdb4:353a:c83f:10::10", 10101)).start(); } }