Multicast Socket using Java Programming Language - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Multicast Socket using Java Programming Language

Share This
MulticastSender.java
import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.SocketException; public class MulticastSender { public static void main(String[] args) { InetAddress ia = null; int port = 0; byte ttl = (byte) 1; // read the address from the command line try { ia = InetAddress.getByName(args[0]); port = Integer.parseInt(args[1]); if (args.length > 2) ttl = (byte) Integer.parseInt(args[2]); } catch (Exception e) { System.err.println(e); System.err.println("Usage: java MulticastSender multicast_address port ttl"); System.exit(1); } byte[] data = "Here's some multicast data\r\n".getBytes(); DatagramPacket dp = new DatagramPacket(data, data.length, ia, port); try { MulticastSocket ms = new MulticastSocket(); ms.joinGroup(ia); for (int i = 1; i < 10; i++) { ms.send(dp, ttl); } ms.leaveGroup(ia); ms.close(); } catch (SocketException se) { System.err.println(se); } catch (IOException ie) { System.err.println(ie); } } }
MulticastSniffer.java
import java.net.*; import java.io.*; public class MulticastSniffer { public static void main(String[] args) { InetAddress group = null; int port = 0; // read the address from the command line try { group = InetAddress.getByName(args[0]); port = Integer.parseInt(args[1]); } // end try catch (Exception e) { // ArrayIndexOutOfBoundsException, NumberFormatException, // or UnknownHostException System.err.println("Usage: java MulticastSniffer multicast_address port"); System.exit(1); } MulticastSocket ms = null; try { ms = new MulticastSocket(port); ms.joinGroup(group); byte[] buffer = new byte[8192]; while (true) { DatagramPacket dp = new DatagramPacket(buffer, buffer.length); ms.receive(dp); String s = new String(dp.getData()); System.out.println(s); } } catch (IOException e) { System.err.println(e); } finally { if (ms != null) { try { ms.leaveGroup(group); ms.close(); } catch (IOException e) { } } } } }

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.