集册 Java实例教程 向一组收件人广播

向一组收件人广播

欢马劈雪     最近更新时间:2020-01-02 10:19:05

462
客户端.java

import java.io.IOException;

import java.net.InetAddress;/** 时代Java - N o w  J a v a . c o m 提供 **/

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) {

    try {

      NetworkInterface networkInterface = null;

      java.util.Enumeration<NetworkInterface> enumNI = NetworkInterface/*来自 NowJava.com - 时代Java*/

          .getNetworkInterfaces();

      java.util.Enumeration<InetAddress> enumIA;

      NetworkInterface ni;

      InetAddress ia;

      ILOOP: while (enumNI.hasMoreElements()) {

        ni = enumNI.nextElement();

        enumIA = ni.getInetAddresses();

        while (enumIA.hasMoreElements()) {

          ia = enumIA.nextElement();

          if (ni.isUp() && ni.supportsMulticast() && !ni.isVirtual()

              && !ni.isLoopback() && !ia.isSiteLocalAddress()) {

            networkInterface = ni;

            break ILOOP;

          }

        }

      }


      // Address within range

      int port = 5239;

      InetAddress group = InetAddress.getByName("226.18.84.25");


      final DatagramChannel client = DatagramChannel

          .open(StandardProtocolFamily.INET);


      client.setOption(StandardSocketOptions.SO_REUSEADDR, true);

      client.bind(new InetSocketAddress(port));

      client.setOption(StandardSocketOptions.IP_MULTICAST_IF, networkInterface);


      System.out.println("Joining group: " + group + " with network interface "

          + networkInterface);

      MembershipKey key = client.join(group, networkInterface);

      client.open();

      final ByteBuffer buffer = ByteBuffer.allocateDirect(4096);

      buffer.clear();

      System.out.println("Waiting to receive message");

      // Configure client to be passive and non.blocking

      // client.configureBlocking(false);

      client.receive(buffer);

      System.out.println(
展开阅读全文