集册 Java实例教程 使用DatagramChannel编写UDP多播服务器

使用DatagramChannel编写UDP多播服务器

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

513
使用DatagramChannel编写UDP组播服务器

import java.io.IOException;// from 时   代    Java - nowjava.com

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.util.Date;


public class Main {

  public static void main(String[] args) {

    ByteBuffer datetime;

    try (DatagramChannel datagramChannel = DatagramChannel
    /*来自 
     N o w  J a v a  . c o m*/

        .open(StandardProtocolFamily.INET)) {

      if (datagramChannel.isOpen()) {

        NetworkInterface networkInterface = NetworkInterface.getByName("test");

        datagramChannel.setOption(StandardSocketOptions.IP_MULTICAST_IF,

            networkInterface);

        datagramChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);

        datagramChannel.bind(new InetSocketAddress(5555));

        while (true) {

          System.out.println("Sending data ...");

          datetime = ByteBuffer.wrap(new Date().toString().getBytes());

          datagramChannel

              .send(datetime,

                  new InetSocketAddress(InetAddress.getByName(
展开阅读全文