首页 > 其他分享 >NIO 实现非阻塞 Socket 通讯

NIO 实现非阻塞 Socket 通讯

时间:2023-04-06 17:22:28浏览次数:34  
标签:NIO 阻塞 selector sk Selector import SelectionKey SocketChannel Socket

NIO 实现多人聊天室的案例

服务端

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;

/**
 * 聊天室服务端
 */
public class NServer {

    private Selector selector = null;

    static final int PORT = 30000;

    private Charset charset = Charset.forName("UTF-8");

    ServerSocketChannel server = null;

    public void init() throws IOException {
        selector = Selector.open();
        server = ServerSocketChannel.open();
        InetSocketAddress isa = new InetSocketAddress("127.0.0.1", PORT);
        // 将该 ServerSocketChannel 绑定到指定 IP 地址
        server.bind(isa);

        //设置为以非阻塞方式工作
        server.configureBlocking(false);
        // 将 server 注册到指定的 Selector
        server.register(selector, SelectionKey.OP_ACCEPT);

        while (selector.select() > 0) {
            for (SelectionKey sk : selector.selectedKeys()) {
                // 从 selector 上的已选择 Key 集中删除正在处理的 SelectionKey
                selector.selectedKeys().remove(sk);
                // 如果 sk 对应 channel 包含客户端的连接请求
                if (sk.isAcceptable()) {
                    // 接受请求
                    SocketChannel sc = server.accept();
                    // 采用非阻塞模式
                    sc.configureBlocking(false);
                    // 将该 SocketChannel 也注册到 selector
                    sc.register(selector, SelectionKey.OP_READ);
                    // 将 sk 对应的 channel 设置成准备接受其他请求
                    sk.interestOps(SelectionKey.OP_ACCEPT);
                }
                // 如果 sk 对应的channel 有数据需要读取
                if (sk.isReadable()) {
                    SocketChannel sc = (SocketChannel) sk.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    String content = "";

                    try {
                        // 读取数据操作
                        while (sc.read(buffer) > 0) {
                            buffer.flip();
                            content += charset.decode(buffer);
                        }
                        System.out.println("读取的数据: " + content);
                        sk.interestOps(SelectionKey.OP_READ);
                    } catch (IOException e) {
                        sk.cancel();
                        if (sk.channel() != null) {
                            sk.channel().close();
                        }
                    }
                    // 如果 content 的长度大于 0,即聊天信息不为空
                    if (content.length() > 0) {
                        // 遍历该 selector 里注册的所有 SelectionKey
                        for (SelectionKey key : selector.keys()) {
                            // 获取 channel
                            Channel targetChannel = key.channel();
                            // 如果该 channel 是 SocketChannel
                            if (targetChannel instanceof SocketChannel) {
                                // 将读到的内容写到该 channel 中
                                SocketChannel dest = (SocketChannel) targetChannel;
                                dest.write(charset.encode(content));
                            }
                        }
                    }
                }
            }
        }

    }

    public static void main(String[] args) throws IOException {
        new NServer().init();
    }

}

启动时建立一个可监听连接请求的 ServerSocketChannel,并注册到 Selector,接着直接采用循环不断监听 Selector 对象的 select() 方法返回值,大于0时,处理该 Selector 上所有被选择的 SelectionKey。

服务端仅需监听两种操作:连接和读取数据。

处理连接操作时,只需将连接完成后产生的 SocketChannel 注册到指定的 Selector 对象;

处理读取数据时,先从该 Socket 中读取数据,再将数据写入 Selector 上注册的所有 Channel 中。

客户端

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.nio.charset.Charset;
import java.util.Scanner;

/**
 * 聊天室客户端
 */
public class NClient {
    private Selector selector = null;
    static final int PORT = 30000;
    private Charset charset = Charset.forName("UTF-8");

    private SocketChannel sc = null;

    public void init() throws IOException {
        selector = Selector.open();
        InetSocketAddress isa = new InetSocketAddress("127.0.0.1", PORT);
        // 打开套接字通道并将其连接到远程地址
        sc = SocketChannel.open(isa);

        // 设置为非阻塞模式
        sc.configureBlocking(false);
        // 注册到 selector
        sc.register(selector, SelectionKey.OP_READ);

        new ClientThread().start();
        // 创建键盘输入流
        Scanner scan = new Scanner(System.in);
        while (scan.hasNextLine()) {
            String line = scan.nextLine();
            // 将键盘大忽如的内容输出到 SocketChannel 中
            sc.write(charset.encode(line));
        }

    }

    private class ClientThread extends  Thread {
        @Override
        public void run() {
            try {
                while (selector.select() > 0) {
                    for (SelectionKey sk : selector.selectedKeys()) {
                        // 从 set集合删除正在处理的 SelectionKey
                        selector.selectedKeys().remove(sk);
                        // 如果 sk 对应的 channel 中有可读数据
                        if (sk.isReadable()) {
                            // 使用 NIO 读取 channel 中的数据
                            SocketChannel sc = (SocketChannel) sk.channel();
                            ByteBuffer buff = ByteBuffer.allocate(1024);
                            String content = "";
                            while (sc.read(buff) > 0) {
                                sc.read(buff);
                                buff.flip();
                                content += charset.decode(buff);
                            }
                            System.out.println("聊天信息: " + content);
                            // 为下一次读取做准备
                            sk.interestOps(SelectionKey.OP_READ);
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new NClient().init();
    }
}

 

相比于服务端程序,客户端要简单一些,只有一个 SocketChannel ,将其注册到指定的 Selector 后,程序启动另一个线程来监听该 Selector 即可。

分别启动两个程序后,可以在客户点输入内容,在服务端就可以读取到输入的内

 

服务端内容:

 

标签:NIO,阻塞,selector,sk,Selector,import,SelectionKey,SocketChannel,Socket
From: https://www.cnblogs.com/jizhixiang/p/17293462.html

相关文章

  • Parallel 会阻塞调用者吗
    提问Parallel会阻塞调用者吗回答会原因虽然parallel也是基于线程池,但是他也会阻塞调用者......
  • WebSocket 实战之——【WebSocket 原理】
    一、WebSocket是什么?HTML5出的东西(协议),也就是说HTTP协议没有变化,或者说没关系,但HTTP是不支持持久连接的(长连接,循环连接的不算)。    首先HTTP有1.1和1.0之说,也就是所谓的keep-alive,把多个HTTP请求合并为一个,但是Websocket其实是一个新协议,跟HTTP协议基本没有关系,只是为了......
  • Java BIO,NIO,AIO
    一丶IO模型&JavaIOUnix为程序员提供了以下5种基本的io模型:blockingio:阻塞iononblockingio:非阻塞ioI/Omultiplexing:io多路复用signaldrivenI/O:信号驱动ioasynchronousI/O:异步io但我们平时工作中说的最多是,阻塞,非阻塞,同步,异步1.阻塞非阻塞,同步异步阻塞调用是......
  • Disjoint-Set-Union Sum (诈骗题)(区间DP, 位置顺序!!!!)
    题目大意: 给出一个序列P,n个点每次可以选择2个相邻区间进行合并,会产生一个贡献值,当然合并n-1就合并完了,问在所有的情况下,贡献和是多少  思路:易错点:这个所有情况,你枚举的合并的那个先后顺序是有关系的!!!因此直接去区间dp只能把各个合并的情况给弄......
  • 使用Async和Await可以实现多任务顺序执行且不阻塞
    使用Async和Await可以实现多任务顺序执行且不阻塞//////////////////////对于async和await的使用方式、作用效果不怎么理解?没关系,初步看这篇就够了 结论同步还是异步,区别如下:同步:你使用 await 修饰符去调用一个异步(async)方法(是异步方法,不过是阻塞式的,可简单理解为同......
  • SuperSocket 服务端 和 SuperSocket.ClientEngine 客户端及普通客户端
    internalclassProgram{//staticvoidMain(string[]args)//{//byte[]arr=newbyte[1024];//1.创建socket对象//Socketsocket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolTyp......
  • java之NIO简介
    一、NIO基本简介NIO (NewlO)也有人称之为javanon-blockinglO是从Java1.4版本开始引入的一个新的IOAPI,可以替代标准的JavalOAPI。NIO与原来的IO有同样的作用和目的,但是使用的方式完全不同,NIO支持面向缓冲区的、基于通道的IO操作。NIO将以更加高效的方式进行文件的读写操......
  • 全面理解WebSocket与Socket、TCP、HTTP的关系及区别
    6.WebSocket和SocketSocket其实并不是一个协议,而是为了方便使用TCP或UDP而抽象出来的一层,是位于应用层和传输控制层之间的一组接口。 Socket本身并不是一个协议,它工作在OSI模型会话层,是一个套接字,TCP/IP网络的API,是为了方便大家直接使用。更底层协议而存在的一个抽象层。S......
  • 搭建redis主从复制集群环境时,当从库执行slaveof命令时报错“Error condition on socke
    问题描述:搭建redis主从复制集群环境时,当从库执行slaveof命令时报错“ErrorconditiononsocketforSYNC:Noroutetohost”,如下所示:操作系统:rhel7.964位数据库:redis6.2.6主机名:主库leo-redis626-a,从库leo-redis626-b.1、异常重现[[email protected]]#p......
  • php-websocket hyperf/websocket-server/client 客户端和服务器实时双向数据传输
    WebSocket服务WebSocket是一种通信协议,可在单个TCP连接上进行全双工通信。WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocketAPI中,浏览器和服务器只需要完成一次握手,两者之间就可以建立持久性的连接,并进行双向数据传输。Hyperf......