【NIO】ServerSocketChannel

xiaoxiao2021-02-28  45

前言

Github:https://github.com/yihonglei/jdk-source-code-reading(java-nio)

一 ServerSocketChannel概述

Java NIO中的ServerSocketChannel类定义在java.nio.channels包中。

ServerSocketChannel是一个可以监听新进来的TCP连接的通道,就像标准IO中的ServerSocket一样。

示例:

// 获得一个ServerSocket通道

ServerSocketChannel serverChannel = ServerSocketChannel.open();

// 设置通道为非阻塞

serverChannel.configureBlocking(false);

// 将该通道对于的serverSocket绑定到port端口,比如8989

serverChannel.socket().bind(new InetSocketAddress(8989));

二 打开ServerSocketChannel

通过调用ServerSocketChannel.open()方法来打开ServerSocketChannel。比如:

// 获得一个ServerSocket通道

ServerSocketChannel serverChannel = ServerSocketChannel.open();

三 关闭ServerSocketChannel

通过调用ServerSocketChannel.close()方法来关闭ServerSocketChannel。比如:

serverSocketChannel.close();

四 监听新进来的连接

通过ServerSocketChannel.accept()方法监听新进来的连接。

当accept()方法返回的时候,它返回一个包含新进来的连接的SocketChannel。

因此, accept()方法会一直阻塞到有新连接到达。通常不会仅仅只监听一个连接,

在while循环中调用 accept()方法. 如下面的例子:

while(true) {

    // 获得和客户端连接的通道

    SocketChannel socketChannel = serverSocketChannel.accept();

   // 设置成非阻塞

   channel.configureBlocking(false);

   // do something with socketChannel...

}

当然,也可以在while循环中使用除了true以外的其它退出准则。

五 非阻塞模式

ServerSocketChannel可以设置成非阻塞模式。在非阻塞模式下,accept()方法会立刻返回,

如果还没有新进来的连接,返回的将是null。 因此,需要检查返回的SocketChannel是否是null,比如:

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

serverSocketChannel.socket().bind(new InetSocketAddress(8989));

// 设置成非阻塞模式

serverSocketChannel.configureBlocking(false);

while (true)  {

    SocketChannel socketChannel = serverSocketChannel.accept();

    if  (socketChannel != null)  {

       // do something with socketChannel...

    }

}

六 完整实例

NIOServer

package com.jpeony.nio.selector; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.nio.ByteBuffer; import java.nio.channels.*; import java.util.Iterator; import java.util.Set; /** * server端实例代码 * * @author yihonglei */ public class NIOServer { // 通道管理器(Selector) private static Selector selector; public static void main(String[] args) throws IOException { // 创建通道管理器(Selector) selector = Selector.open(); // 创建通道ServerSocketChannel ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); // 将通道设置为非阻塞 serverSocketChannel.configureBlocking(false); // 将ServerSocketChannel对应的ServerSocket绑定到指定端口(port) ServerSocket serverSocket = serverSocketChannel.socket(); serverSocket.bind(new InetSocketAddress(8989)); /** * 将通道(Channel)注册到通道管理器(Selector),并为该通道注册selectionKey.OP_ACCEPT事件 * 注册该事件后,当事件到达的时候,selector.select()会返回, * 如果事件没有到达selector.select()会一直阻塞。 */ serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); // 循环处理 while (true) { // 当注册事件到达时,方法返回,否则该方法会一直阻塞 selector.select(); // 获取监听事件 Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = selectionKeys.iterator(); // 迭代处理 while (iterator.hasNext()) { // 获取事件 SelectionKey key = iterator.next(); // 移除事件,避免重复处理 iterator.remove(); // 检查是否是一个就绪的可以被接受的客户端请求连接 if (key.isAcceptable()) { handleAccept(key); } else if (key.isReadable()) {// 检查套接字是否已经准备好读数据 handleRead(key); } } } } /** * 处理客户端连接成功事件 */ private static void handleAccept(SelectionKey key) throws IOException { // 获取客户端连接通道 ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel socketChannel = server.accept(); socketChannel.configureBlocking(false); // 信息通过通道发送给客户端 String msg = "Hello Client!"; socketChannel.write(ByteBuffer.wrap(msg.getBytes())); // 给通道设置读事件,客户端监听到读事件后,进行读取操作 socketChannel.register(selector, SelectionKey.OP_READ); } /** * 监听到读事件,读取客户端发送过来的消息 */ private static void handleRead(SelectionKey key) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); // 从通道读取数据到缓冲区 ByteBuffer buffer = ByteBuffer.allocate(128); channel.read(buffer); // 输出客户端发送过来的消息 byte[] data = buffer.array(); String msg = new String(data).trim(); System.out.println("server received msg from client:" + msg); } }

NIOClient

package com.jpeony.nio.selector; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; /** * client实例代码 * * @author yihonglei */ public class NIOClient { // 通道管理器(Selector) private static Selector selector; public static void main(String[] args) throws IOException { // 创建通道管理器(Selector) selector = Selector.open(); // 创建通道SocketChannel SocketChannel channel = SocketChannel.open(); // 将通道设置为非阻塞 channel.configureBlocking(false); // 客户端连接服务器,其实方法执行并没有实现连接,需要在handleConnect方法中调channel.finishConnect()才能完成连接 channel.connect(new InetSocketAddress("localhost", 8989)); /** * 将通道(Channel)注册到通道管理器(Selector),并为该通道注册selectionKey.OP_CONNECT * 注册该事件后,当事件到达的时候,selector.select()会返回, * 如果事件没有到达selector.select()会一直阻塞。 */ channel.register(selector, SelectionKey.OP_CONNECT); // 循环处理 while (true) { /* * 选择一组可以进行I/O操作的事件,放在selector中,客户端的该方法不会阻塞, * selector的wakeup方法被调用,方法返回,而对于客户端来说,通道一直是被选中的 * 这里和服务端的方法不一样,查看api注释可以知道,当至少一个通道被选中时。 */ selector.select(); // 获取监听事件 Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = selectionKeys.iterator(); // 迭代处理 while (iterator.hasNext()) { // 获取事件 SelectionKey key = iterator.next(); // 移除事件,避免重复处理 iterator.remove(); // 检查是否是一个就绪的已经连接服务端成功事件 if (key.isConnectable()) { handleConnect(key); } else if (key.isReadable()) {// 检查套接字是否已经准备好读数据 handleRead(key); } } } } /** * 处理客户端连接服务端成功事件 */ private static void handleConnect(SelectionKey key) throws IOException { // 获取与服务端建立连接的通道 SocketChannel channel = (SocketChannel) key.channel(); if (channel.isConnectionPending()) { // channel.finishConnect()才能完成连接 channel.finishConnect(); } channel.configureBlocking(false); // 数据写入通道 String msg = "Hello Server!"; channel.write(ByteBuffer.wrap(msg.getBytes())); // 通道注册到选择器,并且这个通道只对读事件感兴趣 channel.register(selector, SelectionKey.OP_READ); } /** * 监听到读事件,读取客户端发送过来的消息 */ private static void handleRead(SelectionKey key) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); // 从通道读取数据到缓冲区 ByteBuffer buffer = ByteBuffer.allocate(128); channel.read(buffer); // 输出服务端响应发送过来的消息 byte[] data = buffer.array(); String msg = new String(data).trim(); System.out.println("client received msg from server:" + msg); } }

 

转载请注明原文地址: https://www.6miu.com/read-2628880.html

最新回复(0)