Netty NIO 非阻塞模式

1.概要

1.1 说明

使用非阻塞的模式,就可以用一个现场,处理多个客户端的请求了

1.2 要点

  • ssc.configureBlocking(false);
  • if(sc!=null){ sc.configureBlocking(false); channels.add(sc); }
  • if(len>0){ byteBuffer.flip();

2.代码

2.1 服务端代码

复制代码
package com.xjc.springcloundtest;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.net.SocketOption;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class Main {
    public static void main(String[] args) throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(16);
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(8080));
        List<SocketChannel> channels = new ArrayList<>();
        while (true){
            System.out.println("accept 前");
            SocketChannel sc = ssc.accept();
            System.out.println("accept 后");
            if(sc!=null){
                sc.configureBlocking(false);
                channels.add(sc);
            }
            for (SocketChannel channel: channels){
                System.out.println("read 后");
                int len = channel.read(byteBuffer);
                if(len>0){
                    byteBuffer.flip();
                    while (byteBuffer.hasRemaining()){
                        byte b = byteBuffer.get();
                        System.out.println((char)b);
                    }
                    byteBuffer.clear();
                    System.out.println("read 后");
                }
            }
        }
        //System.out.println("Hello world!");
    }
}

2.2 客户端代码

复制代码
package com.xjc.springcloundtest;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;

public class Client {
    public static void main(String[] args) throws IOException {
        SocketChannel sc = SocketChannel.open();
        sc.connect(new InetSocketAddress("localhost", 8080));
        System.out.println("Hello world!");
    }
}

2.2 客户端发数据

复制代码
sc.write(Charset.defaultCharset().encode("hello")

3.运行结果

3.1 服务端结果

3.2 客户端结果

复制代码
2023.3.2\lib\idea_rt.jar" com.xjc.springcloundtest.Client
Connected to the target VM, address: '127.0.0.1:53167', transport: 'socket'
Hello world!
相关推荐
9527出列4 天前
探索服务端启动流程
netty·源码阅读
深圳蔓延科技6 天前
NioEventLoopGroup 完全指南
netty
深圳蔓延科技7 天前
如何使用 Netty 实现 NIO 方式发送 HTTP 请求
netty
码luffyliu8 天前
Java NIO 核心原理与秋招高频面试题解析
java·nio
带只拖鞋去流浪9 天前
Java文件读写(IO、NIO)
java·开发语言·nio
liangsheng_g13 天前
Kafka服务端NIO操作原理解析
后端·kafka·nio
leo__52013 天前
Java的NIO体系详解
java·python·nio
Derek_Smart13 天前
Netty 客户端与服务端选型分析:下位机连接场景
spring boot·后端·netty
Derek_Smart15 天前
工业级TCP客户端高可靠连接架构设计与Netty优化实践
java·性能优化·netty
c_zyer17 天前
FreeSWITCH与Java交互实战:从EslEvent解析到Spring Boot生态整合的全指南
spring boot·netty·freeswitch·eslevent