Java Network Tutorial - Java Network UDP Multicast








Java uses MulticastSocket class to create UDP multicast sockets to receive datagram packets sent to a multicast IP address.

A multicast socket is based on a group membership. After creating and bounding a multicast socket, call its joinGroup(InetAddress multiCastIPAddress) method to join the multicast group, any datagram packet sent to that group will be delivered to this socket.

To leave a group, call the leaveGroup(InetAddress multiCastIPAddress) method.

In IPv4, any IP address in the range 224.0.0.0 to 239.255.255.255 can be used as a multicast address to send a datagram packet.

The IP address 224.0.0.0 is reserved and you should not use it in your application.

A multicast IP address cannot be used as a source address for a datagram packet.





Example

A UDP Multicast Socket That Receives UDP Multicast Messages.

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
/*  ww  w .j av  a 2 s .c  o  m*/
public class Main {
  public static void main(String[] args) throws Exception {
    int mcPort = 12345;
    String mcIPStr = "230.1.1.1";
    MulticastSocket mcSocket = null;
    InetAddress mcIPAddress = null;
    mcIPAddress = InetAddress.getByName(mcIPStr);
    mcSocket = new MulticastSocket(mcPort);
    System.out.println("Multicast Receiver running at:"
        + mcSocket.getLocalSocketAddress());
    mcSocket.joinGroup(mcIPAddress);

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

    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();
  }
}

The code above generates the following result.





Example 2

A UDP Datagram Socket, a Multicast Sender Application.

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/*from   www .j  av a2 s. c  o  m*/
public class Main {
  public static void main(String[] args) throws Exception {
    int mcPort = 12345;
    String mcIPStr = "230.1.1.1";
    DatagramSocket udpSocket = new DatagramSocket();

    InetAddress mcIPAddress = InetAddress.getByName(mcIPStr);
    byte[] msg = "Hello".getBytes();
    DatagramPacket packet = new DatagramPacket(msg, msg.length);
    packet.setAddress(mcIPAddress);
    packet.setPort(mcPort);
    udpSocket.send(packet);

    System.out.println("Sent a  multicast message.");
    System.out.println("Exiting application");
    udpSocket.close();
  }
}

The code above generates the following result.