集册 Java实例教程 数据通道

数据通道

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

525
基于DatagramChannel的多播客户端程序

import java.io.IOException;

import java.net.InetAddress;

import java.net.InetSocketAddress;

import java.net.NetworkInterface;
/**
 from
* 时 代 J a v a 公 众 号 - nowjava.com 
**/

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;

    try (DatagramChannel client = DatagramChannel

        .open(StandardProtocolFamily.INET)) {

      NetworkInterface interf = NetworkInterface

          .getByName("test");


      client.setOption(StandardSocketOptions.SO_REUSEADDR, true);/*来自 N o  w  J a v a . c o m - 时  代  Java*/

      client.bind(new InetSocketAddress(5555));

      client.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);


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

      key = client.join(group, interf);


      System.out.println("Joined the multicast group:" + key);

      System.out.println("Waiting for a message from the"

          + " multicast group....");


      ByteBuffer buffer = ByteBuffer.allocate(1048);


      client.receive(buffer);


      buffer.flip();

      int limits = buffer.limit();

      byte bytes[] = new byte[limits];

      buffer.get(bytes, 0, limits);

      
展开阅读全文