Home  >  Core Java

Example of MembershipKey in Java NIO Channels

By Arvind Rai, November 24, 2013
java.nio.channels.MembershipKey is a token. In a multicast group, when any datagram packet is sent, then it can only be received if receiver has MembershipKey. MembershipKey is valid until it is dropped by drop() method. We can check MembershipKey validity by MembershipKey .isValid() method. Once dropped, MembershipKey will be invalidated.

SelectableChannelTest.java
package com.concretepage.nio.channels;
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.channels.DatagramChannel;
import java.nio.channels.MembershipKey;
import java.util.Enumeration;
public class SelectableChannelTest {
  public static void main(String[] args) throws IOException {
	  Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
	  NetworkInterface ni = null;
	  //Retrieve Network Interface 
      while (en.hasMoreElements()) {
    	  ni = en.nextElement();
    	  System.out.println("Network Interface Name: "+ni.getName());
    	  break;
      }
      //Creates DatagramChannel instances
      DatagramChannel dmChannel = DatagramChannel.open(StandardProtocolFamily.INET);
      
      dmChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
      dmChannel.bind(new InetSocketAddress(1000));
      dmChannel.setOption(StandardSocketOptions.IP_MULTICAST_IF, ni);

      InetAddress address = InetAddress.getByName("225.4.5.6");
      //Generates member ship key
      MembershipKey mkey = dmChannel.join(address, ni);
      
      System.out.println("MembershipKey: "+mkey);
      System.out.println(mkey.isValid());
      
      //MembershipKey can be dropped by drop method
      mkey.drop();
      
      System.out.println(mkey.isValid());
  }
  
}
 
Output
Network Interface Name: lo
MembershipKey: <225.4.5.6,lo>
true
false
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us