A DatagramChannel-Based Multicast Program That Sends a Message to a Multicast Group - Java Network

Java examples for Network:Datagram Channel

Description

A DatagramChannel-Based Multicast Program That Sends a Message to a Multicast Group

Demo Code

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

public class Main {
  public static void main(String[] args) {
    try (DatagramChannel server = DatagramChannel.open()) {
      server.bind(null);/*from   w w  w .j  a va  2  s  .c o m*/
      NetworkInterface interf = NetworkInterface.getByName("test");
      server.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);
      String msg = "Hello from multicast!";
      ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
      InetSocketAddress group = new InetSocketAddress("127.0.0.1", 5555);
      server.send(buffer, group);

      System.out.println("Sent the multicast message: " + msg);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

}

Related Tutorials