集册 Java实例教程 使用DatagramChannel编写UDP多播客户端

使用DatagramChannel编写UDP多播客户端

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

487
使用DatagramChannel编写UDP组播客户端
/*来自 时 代 J a v a 公 众 号 - nowjava.com*/

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.CharBuffer;

import java.nio.channels.DatagramChannel;

import java.nio.channels.MembershipKey;

import java.nio.charset.Charset;

import java.nio.charset.CharsetDecoder;


public class Main {/*来自 NowJava.com*/

  public static void main(String[] args) {

    CharBuffer charBuffer = null;

    Charset charset = Charset.defaultCharset();

    CharsetDecoder decoder = charset.newDecoder();

    ByteBuffer datetime = ByteBuffer.allocateDirect(65507);

    try (DatagramChannel datagramChannel = DatagramChannel

        .open(StandardProtocolFamily.INET)) {

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

      if (group.isMulticastAddress()) {

        if (datagramChannel.isOpen()) {

          NetworkInterface networkInterface = NetworkInterface

              .getByName("test");

          datagramChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);

          datagramChannel.bind(new InetSocketAddress(5555));

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

          while (true) {

            if (key.isValid()) {

              datagramChannel.receive(datetime);

              datetime.flip();

              charBuffer = decoder.decode(datetime);

              System.out.println(charBuffer.toString());

              datetime.clear();

            } else {

              
展开阅读全文