Differences

This shows you the differences between two versions of the page.

Link to this comparison view

javamulticast [2014/10/26 01:52] (current)
Line 1: Line 1:
 +===== Multicast packets in Java =====
 +
 +* Send multicast packets in Java
 +
 +<code 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++;
 + }
 +    }
 +
 +}
 +</​code>​
 +
 +* Receive multicast packets in Java
 +
 +<code 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) {}
 + }
 +    }
 +
 +}
 +</​code>​
 +
 +----
 +* [[javainfo|Back to Java]]
  
javamulticast.txt ยท Last modified: 2014/10/26 01:52 (external edit)
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0