Monday, August 25, 2014

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class MulticastNode {

InetAddress group = null;
MulticastSocket s = null;

public static void main(String[] args) {

if (args.length > 0) {

System.out.println("Sending message: " + args[0]);

MulticastNode node = new MulticastNode();

node.send(args[0]);

node.receive();


} else {

System.out.println("Need an argument string to send.");
System.exit(1);

}

}

public MulticastNode() {

try {

group = InetAddress.getByName("228.0.0.4");
s = new MulticastSocket(45564);
s.joinGroup(group);

} catch (Exception e) {

e.printStackTrace();

}

}

public void send (String msg) {

try {

DatagramPacket hi = new DatagramPacket(
msg.getBytes(), msg.length(),group,45564);
s.send(hi);

} catch (Exception e) {

e.printStackTrace();

}
}

public void receive() {

byte[] buf;

while (true) {


try {

buf = new byte[1000];
DatagramPacket recv = new DatagramPacket(buf, buf.length);
s.receive(recv);
System.out.println("Received: " + new String(buf));

} catch (Exception e) {

e.printStackTrace();

}

}

}

}



to test.
Copy to a test directory on each machine you want to test.
Then run "$JAVA_HOME/bin/java MulticastNode NodeOne" on the first node.
On the second node ""$JAVA_HOME/bin/java MulticastNode NodeTwo"
You will first see:
>java MulticastNode NodeOne
Sending message: NodeOne
Received: NodeOne
on the first node, then when starting on second:

This is from pages 374-378 of "Tomcat the definitive guide" from O'Reilly.

No comments:

Post a Comment