Java DatagramChannel create multicast server

Description

Java DatagramChannel create multicast server


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);//  ww  w.  j a  v a 2  s  .  c om

      NetworkInterface interf = NetworkInterface.getByName("eth3");

      server.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);

      String msg = "Hello from multicast!";
      ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
      InetSocketAddress group = new InetSocketAddress("yourIP", 8989);

      server.send(buffer, group);

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



PreviousNext

Related