Java DatagramChannel create multicast client

Description

Java DatagramChannel create multicast client


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

public class Main {
  public static void main(String[] args) {
    MembershipKey key = null;/*from  w  w  w  .j av  a2s.  c  o  m*/

    try (DatagramChannel client = DatagramChannel.open(StandardProtocolFamily.INET)) {
      NetworkInterface interf = NetworkInterface.getByName("eth3");

      client.setOption(StandardSocketOptions.SO_REUSEADDR, true);
      client.bind(new InetSocketAddress(8989));
      client.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);

      InetAddress group = InetAddress.getByName("yourIP");
      key = client.join(group, interf);

      System.out.println("Joined the multicast group:" + key);
      System.out.println("Waiting for a message from the" + " multicast group....");

      // Prepare a data buffer to receive a message from the multi cast group
      ByteBuffer buffer = ByteBuffer.allocate(1048);

      // Wait to receive a message from the multi cast group
      client.receive(buffer);

      // Convert the message in the ByteBuffer into a string
      buffer.flip();
      int limits = buffer.limit();
      byte bytes[] = new byte[limits];
      buffer.get(bytes, 0, limits);
      String msg = new String(bytes);

      System.out.println("Multicast Message:"+ msg);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
       if (key != null) {
        key.drop();
      }
    }
  }
}



PreviousNext

Related