Java 數(shù)據(jù)報套接字通道

2018-02-28 16:28 更新

Java網(wǎng)絡教程 - Java數(shù)據(jù)報套接字通道


java.nio.channels.DatagramChannel類表示數(shù)據(jù)報通道。默認情況下,它是阻塞。要使其無阻塞,請使用configureBlocking(false)方法。

要創(chuàng)建 DatagramChannel ,請調用其 open()靜態(tài)方法之一。

要將其用于IP多播,請將多播組的地址類型指定為其 open()方法的參數(shù)。

open()方法創(chuàng)建一個沒有連接的DatagramChannel對象。

例子

以下代碼顯示如何基于數(shù)據(jù)報通道創(chuàng)建Echo服務器。

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

public class Main {
  public static void main(String[] args) throws Exception {
    DatagramChannel server = null;
    server = DatagramChannel.open();
    InetSocketAddress sAddr = new InetSocketAddress("localhost", 8989);
    server.bind(sAddr);
    ByteBuffer buffer = ByteBuffer.allocate(1024);

    while (true) {
      System.out.println("Waiting for a  message  from"
          + "  a  remote  host at " + sAddr);
      SocketAddress remoteAddr = server.receive(buffer);
      buffer.flip();
      int limits = buffer.limit();
      byte bytes[] = new byte[limits];
      buffer.get(bytes, 0, limits);
      String msg = new String(bytes);

      System.out.println("Client at " + remoteAddr + "  says: " + msg);
      buffer.rewind();
      server.send(buffer, remoteAddr);
      buffer.clear();
    }
    //server.close();
  }
}

上面的代碼生成以下結果。


例2

以下代碼基于數(shù)據(jù)報通道創(chuàng)建客戶端程序。

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

public class Main {
  public static void main(String[] args) throws Exception {
    DatagramChannel client = null;
    client = DatagramChannel.open();

    client.bind(null);

    String msg = "Hello";
    ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
    InetSocketAddress serverAddress = new InetSocketAddress("localhost",
        8989);

    client.send(buffer, serverAddress);
    buffer.clear();
    client.receive(buffer);
    buffer.flip();
    int limits = buffer.limit();
    byte bytes[] = new byte[limits];
    buffer.get(bytes, 0, limits);
    String response = new String(bytes);
    System.out.println("Server  responded: " + response);
    client.close();
  }
}

上面的代碼生成以下結果。


列出機器上的可用網(wǎng)絡接口

import java.net.NetworkInterface;
import java.util.Enumeration;

public class Main {
  public static void main(String[] args) throws Exception {
    Enumeration<NetworkInterface> e = NetworkInterface
        .getNetworkInterfaces();
    while (e.hasMoreElements()) {
      NetworkInterface nif = e.nextElement();
      System.out.println("Name: " + nif.getName()
          + ",  Supports Multicast: " + nif.supportsMulticast()
          + ", isUp(): " + nif.isUp());
    }
  }
}

上面的代碼生成以下結果。

例3

以下代碼基于DatagramChannel的組播客戶端程序

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.nio.channels.MembershipKey;

public class Main {
  public static final String MULTICAST_IP = "239.1.1.1";
  public static final int MULTICAST_PORT = 8989;

  public static final String MULTICAST_INTERFACE_NAME = "eth1";

  public static void main(String[] args) throws Exception {
    MembershipKey key = null;
    DatagramChannel client = DatagramChannel.open(StandardProtocolFamily.INET);

    NetworkInterface interf = NetworkInterface.getByName(MULTICAST_INTERFACE_NAME);
    client.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    client.bind(new InetSocketAddress(MULTICAST_PORT));
    client.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);

    InetAddress group = InetAddress.getByName(MULTICAST_IP);
    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);
    String msg = new String(bytes);

    System.out.format("Multicast Message:%s%n", msg);
    key.drop();
  }
}

上面的代碼生成以下結果。

例4

以下代碼顯示如何創(chuàng)建向多播組發(fā)送消息的基于DatagramChannel的組播程序。

import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

public class Main {
  public static final String MULTICAST_IP = "239.1.1.1";
  public static final int MULTICAST_PORT = 8989;
  public static final String MULTICAST_INTERFACE_NAME = "eth1";

  public static void main(String[] args) throws Exception {
    DatagramChannel server = DatagramChannel.open();
    server.bind(null);
    NetworkInterface interf = NetworkInterface
        .getByName(MULTICAST_INTERFACE_NAME);
    server.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);

    String msg = "Hello!";
    ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
    InetSocketAddress group = new InetSocketAddress(MULTICAST_IP,
        MULTICAST_PORT);

    server.send(buffer, group);
    System.out.println("Sent the   multicast  message: " + msg);
  }
}

上面的代碼生成以下結果。

以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號