A UDP Multicast Socket That Receives UDP Multicast Messages - Java Network

Java examples for Network:UDP

Description

A UDP Multicast Socket That Receives UDP Multicast Messages

Demo Code

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

public class Main {
  public static void main(String[] args) throws Exception {
    InetAddress mcIPAddress = InetAddress.getByName("127.0.0.1");
    MulticastSocket mcSocket = new MulticastSocket(5555);
    System.out.println("Multicast Receiver running at:"
        + mcSocket.getLocalSocketAddress());
    mcSocket.joinGroup(mcIPAddress);//from   ww  w . j ava2s .c om

    DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);

    while (true) {
      System.out.println("Waiting for a multicast message...");
      mcSocket.receive(packet);
      String msg = new String(packet.getData(), packet.getOffset(),
          packet.getLength());
      System.out.println("[Multicast Receiver] Received:" + msg);
    }
    // mcSocket.leaveGroup(mcIPAddress);
    // mcSocket.close();
  }
}

Related Tutorials