package jp.vmi; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.SocketException; import java.net.UnknownHostException; import java.nio.charset.Charset; public class Multicast { private static final Charset UTF8 = Charset.forName("UTF-8"); private final InetAddress addr; private final int port; private Sender sender = null; private Receiver receiver = null; public Multicast(String host, int port) throws UnknownHostException { this.addr = InetAddress.getByName(host); this.port = port; } public class Sender { private final DatagramSocket socket; public Sender() throws SocketException { socket = new DatagramSocket(); } public void send(String msg) throws IOException { byte[] data = msg.getBytes(UTF8); DatagramPacket packet = new DatagramPacket(data, data.length, addr, port); socket.send(packet); } } synchronized public Sender getSender() throws SocketException { if (sender == null) sender = new Sender(); return sender; } public class Receiver { private final MulticastSocket socket; private final byte[] buffer = new byte[8 * 1024 + 1]; private final DatagramPacket packet = new DatagramPacket(buffer, buffer.length); public Receiver() throws IOException { socket = new MulticastSocket(port); socket.joinGroup(addr); } public String receive() throws IOException { socket.receive(packet); int off = packet.getOffset(); int len = packet.getLength(); return new String(buffer, off, len, UTF8); } public InetAddress getAddress() { return packet.getAddress(); } } synchronized public Receiver getReceiver() throws IOException { if (receiver == null) receiver = new Receiver(); return receiver; } }