集册 Java实例教程 数据通道

数据通道

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

525
基于DatagramChannel的多播程序,向多播组发送消息

import java.io.IOException;

import java.net.InetSocketAddress;
/*来自 
 N o w J a v a . c o m - 时  代  Java*/

import java.net.NetworkInterface;

import java.net.StandardSocketOptions;

import java.nio.ByteBuffer;

import java.nio.channels.DatagramChannel;


public class Main {

  public static void main(String[] args) {

    try (DatagramChannel server = DatagramChannel.open()) {

      server.bind(null);

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

      server.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);

      String msg = "Hello from multicast!";

      ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());

      InetSocketAddress group = new InetSocketAddress("127.0.0.1", 5555);

      server.send(buffer, group);
展开阅读全文