Java NIO - 資料報通道



Java NIO 資料報通道用於透過無連線協議傳送和接收 UDP 資料包。預設情況下,資料報通道是阻塞的,但也可以在非阻塞模式下使用。為了使其變為非阻塞模式,可以使用 `configureBlocking(false)` 方法。資料報通道可以透過呼叫其靜態方法 `open()` 來開啟,該方法也可以接受 IP 地址作為引數,以便用於多播。

與檔案通道類似,資料報通道預設情況下未連線。為了使其連線,必須顯式呼叫其 `connect()` 方法。但是,資料報通道無需連線即可使用傳送和接收方法,而必須連線才能使用讀取和寫入方法,因為這些方法不接受或返回套接字地址。

可以透過呼叫其 `isConnected()` 方法來檢查資料報通道的連線狀態。連線後,資料報通道將保持連線狀態,直到其斷開連線或關閉。資料報通道是執行緒安全的,並且同時支援多執行緒和併發。

資料報通道的重要方法

  • bind(SocketAddress local) − 此方法用於將資料報通道的套接字繫結到作為此方法引數提供的本地地址。

  • connect(SocketAddress remote) − 此方法用於將套接字連線到遠端地址。

  • disconnect() − 此方法用於斷開與遠端地址的套接字連線。

  • getRemoteAddress() − 此方法返回通道的套接字連線到的遠端位置的地址。

  • isConnected() − 如前所述,此方法返回資料報通道的連線狀態,即它是已連線還是未連線。

  • open() 和 open(ProtocolFamily family) − `open()` 方法用於為單個地址開啟資料報通道,而帶引數的 `open()` 方法則為表示為協議族的多個地址開啟通道。

  • read(ByteBuffer dst) − 此方法用於透過資料報通道從給定的緩衝區讀取資料。

  • receive(ByteBuffer dst) − 此方法用於透過此通道接收資料報。

  • send(ByteBuffer src, SocketAddress target) − 此方法用於透過此通道傳送資料報。

示例

以下示例演示如何從 Java NIO DataGramChannel 傳送資料。

伺服器:DatagramChannelServer.java

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

public class DatagramChannelServer {
   public static void main(String[] args) throws IOException {
      DatagramChannel server = DatagramChannel.open();
      InetSocketAddress iAdd = new InetSocketAddress("localhost", 8989);
      server.bind(iAdd);
      System.out.println("Server Started: " + iAdd);
      ByteBuffer buffer = ByteBuffer.allocate(1024);
      //receive buffer from client.
      SocketAddress remoteAdd = server.receive(buffer);
      //change mode of 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 " + remoteAdd + "  sent: " + msg);
      server.send(buffer,remoteAdd);
      server.close();
   }
}

輸出

Server Started: localhost/127.0.0.1:8989

客戶端:DatagramChannelClient.java

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

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

      client.bind(null);

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

      client.send(buffer, serverAddress);
      buffer.clear();
      client.receive(buffer);
      buffer.flip();
    
      client.close();
   }
}

輸出

執行客戶端將在伺服器上列印以下輸出。

Server Started: localhost/127.0.0.1:8989
Client at /127.0.0.1:64857  sent: Hello World!
廣告
© . All rights reserved.