Java NIO - ServerSocketChannel

Java NIO - ServerSocketChannel 首页 / Nio入门教程 / Java NIO - ServerSocketChannel

Server Socket Channel可以通过调用其静态open()方法来创建,然后通过调用 bind()方法进行绑定。

通过ServerSocketChannel.accept()方法来侦听服务器Socket通道的传入连接。当accept()方法返回时,它将返回带有传入连接的SocketChannel。因此,accept()方法将阻塞直到传入连接到达为止。

就像Socket通道服务器一样,Socket通道可以使用 read()方法读取数据。从ServerSocketChannel读取的数据存储在缓冲区中。其次,无涯教程调用ServerSocketChannel.read()方法,它将数据从ServerSocketChannel读取到缓冲区中。 read()方法的整数值返回将多少字节写入缓冲区

类似地,可以使用 write()方法将数据写入服务器Socket通道,在while循环中使用write方法,需要重复执行write()方法直到Buffer写满。

重要函数

  • bind(SocketAddress local)                              - 此方法用于将Socket通道绑定到本地地址。

  • accept()                                                                - 此方法用于接受与此通道的Socket创建的连接。

  • connect(SocketAddress remote)                    - 此方法用于将Socket连接到远程地址。

  • finishConnect()                                                  - 此方法用于完成Socket通道的连接过程。

  • getRemoteAddress()                                         - 此方法返回通道Socket连接到的远程位置的地址。

  • isConnected()                                                     - 如前所述,该方法返回Socket通道的连接状态,即是否已连接。

  • open()                                                                  - 使用open方法打开一个没有指定地址的Socket通道

  • read(ByteBuffer dst)                                         - 此方法用于通过Socket通道从给定的缓冲区读取数据。

  • setOption(SocketOption name, T value)   - 此方法设置套接字选项的值。

  • socket()                                                                - 此方法检索与此通道关联的服务器Socket。

  • validOps()                                                           - 此方法返回标识此通道支持的操作的操作集。服务器Socket通道仅支持接受新连接,因此此方法返回SelectionKey.OP_ACCEPT。

ServerSocketChannel 示例

以下示例显示了如何从Java NIO ServerSocketChannel发送数据。

C:/Test/temp.

Hello World!

客户端代码

SocketChannelClient.java

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;

public class SocketChannelClient {
   public static void main(String[] args) throws IOException {
      ServerSocketChannel serverSocket = null;
      SocketChannel client = null;
      serverSocket = ServerSocketChannel.open();
      serverSocket.socket().bind(new InetSocketAddress(9000));
      client = serverSocket.accept();
      System.out.println("Connection Set:  " + client.getRemoteAddress());
      Path path = Paths.get("C:/Test/temp1.txt");
      FileChannel fileChannel = FileChannel.open(path, 
         EnumSet.of(StandardOpenOption.CREATE, 
            StandardOpenOption.TRUNCATE_EXISTING,
            StandardOpenOption.WRITE)
         );      
      ByteBuffer buffer = ByteBuffer.allocate(1024);
      while(client.read(buffer) > 0) {
         buffer.flip();
         fileChannel.write(buffer);
         buffer.clear();
      }
      fileChannel.close();
      System.out.println("File Received");
      client.close();
   }
}

在服务器启动之前,运行客户端将不会打印任何内容。

无涯教程网

服务器代码

SocketChannelServer.java

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;

public class SocketChannelServer {
   public static void main(String[] args) throws IOException {
      SocketChannel server = SocketChannel.open();
      SocketAddress socketAddr = new InetSocketAddress("localhost", 9000);
      server.connect(socketAddr);
      Path path = Paths.get("C:/Test/temp.txt");
      FileChannel fileChannel = FileChannel.open(path);
      ByteBuffer buffer = ByteBuffer.allocate(1024);
      while(fileChannel.read(buffer) > 0) {
         buffer.flip();
         server.write(buffer);
         buffer.clear();
      }
      fileChannel.close();
      System.out.println("File Sent");
      server.close();
   }
}

运行服务器将打印以下内容。

Connection Set:  /127.0.0.1:49558
File Received

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

TensorFlow快速入门与实战 -〔彭靖田〕

许式伟的架构课 -〔许式伟〕

深入拆解Tomcat & Jetty -〔李号双〕

系统性能调优必知必会 -〔陶辉〕

技术管理案例课 -〔许健〕

基于人因的用户体验设计课 -〔刘石〕

操作系统实战45讲 -〔彭东〕

Tony Bai · Go语言第一课 -〔Tony Bai〕

云计算的必修小课 -〔吕蕴偲〕

好记忆不如烂笔头。留下您的足迹吧 :)