Create Multicast Receiver using MulticastSocket - Java Network

Java examples for Network:UDP

Description

Create Multicast Receiver using MulticastSocket

Demo Code

import java.io.*;
import java.net.*;

public class MulticastReceiver {
  public static void main(String[] args) {
    DatagramPacket inPacket = null;
    byte[] inBuf = new byte[256];
    try {/* w ww.  ja  va 2 s .  c  o m*/
      //Prepare to join multicast group
      MulticastSocket socket = new MulticastSocket(8888);
      InetAddress address = InetAddress.getByName("224.2.2.3");
      socket.joinGroup(address);

      while (true) {
        inPacket = new DatagramPacket(inBuf, inBuf.length);
        socket.receive(inPacket);
        String msg = new String(inBuf, 0, inPacket.getLength());
        System.out.println("From " + inPacket.getAddress() + " Msg : " + msg);
      }
    } catch (IOException ioe) {
      System.out.println(ioe);
    }
  }
}

Related Tutorials