Skip to content

Instantly share code, notes, and snippets.

@nori3tsu
Last active August 29, 2015 14:07
Show Gist options
  • Save nori3tsu/e459141c8f48b9831af9 to your computer and use it in GitHub Desktop.
Save nori3tsu/e459141c8f48b9831af9 to your computer and use it in GitHub Desktop.
マルチキャスト通信検証用
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
/**
* マルチキャスト通信検証用
* 各ホストでjarを起動してマルチキャスト通信が可能か検証する。
* $ java -jar multicast.jar [message]
*/
public class MulticastNode {
private static final String ADDRESS = "228.0.0.4";
private static final int PORT = 60000;
private InetAddress group;
private MulticastSocket sock;
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.out.println("Need an argument string to send.");
System.exit(1);
}
String msg = args[0];
System.out.printf("Sending message: %s\n", msg);
MulticastNode node = new MulticastNode();
node.send(msg);
node.receive();
}
public MulticastNode() throws IOException {
group = InetAddress.getByName(ADDRESS);
sock = new MulticastSocket(PORT);
sock.joinGroup(group);
}
public void send(String msg) throws IOException {
DatagramPacket hi = new DatagramPacket(msg.getBytes(),
msg.length(),
group,
PORT);
sock.send(hi);
}
public void receive() throws IOException {
byte[] buf;
while (true) {
buf = new byte[1000];
DatagramPacket recv = new DatagramPacket(buf, buf.length);
sock.receive(recv);
System.out.printf("Received: %s\n", new String(buf));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment