* Send multicast packets in Java
import java.net.*; public class MCastSend { public static void main(String args[]) throws Exception { if (args.length < 2) { System.out.println("need group and port... exiting."); System.exit(1); } InetAddress group = InetAddress.getByName(args[0]); int port = Integer.parseInt(args[1]); MulticastSocket s = new MulticastSocket(16000);//port); s.setTimeToLive(5); s.joinGroup(group); byte buf[] = new byte[12]; DatagramPacket msg = new DatagramPacket(buf, buf.length, group,port); byte i = 0; while (true) { buf[0] = i; buf[1] = (byte) 0; try { System.out.println("Send " + buf[0]); s.send(msg); Thread.sleep(1000); } catch (Exception e) {} i++; } } }
* Receive multicast packets in Java
import java.net.*; public class MCastRecv { public static void main(String args[]) throws Exception { if (args.length == 0) { System.out.println("need group and port... exiting."); System.exit(1); } InetAddress group = InetAddress.getByName(args[0]); int port = Integer.parseInt(args[1]); MulticastSocket s = new MulticastSocket(port); s.joinGroup(group); byte buf[] = new byte[12]; DatagramPacket msg = new DatagramPacket(buf, buf.length, group,port); int i = 0; while (true) { try { s.receive(msg); InetAddress from = msg.getAddress(); int len = msg.getLength(); byte inbuf[]; inbuf = msg.getData(); System.out.print("recvd mcast msg " + i++ + " from " + from.getHostAddress() + " len = " +len + " "); int seq = inbuf[0]; System.out.println(seq); } catch (Exception e) {} } } }