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!
相关推荐
星辰_mya5 天前
Netty实战——即时通讯IM
netty
Serene_Dream5 天前
NIO 的底层机理
java·jvm·nio·mmap
ps酷教程6 天前
HttpPostRequestEncoder源码浅析
http·netty
强化试剂8 天前
Ergosterol-PEG-Biotin,麦角甾醇PEG生物素在生物偶联中的关键应用
jvm·intellij-idea·mybatis·nio
what丶k9 天前
深入理解Java NIO:从原理到实战的全方位解析
java·开发语言·nio
YRYDZFtyVKg12 天前
探索三菱R系列PLC程序:以ST语言为核心的高效编程之路
nio
笨手笨脚の14 天前
Linux JDK NIO 源码分析
java·linux·nio
ps酷教程16 天前
netty模拟文件列表http服务器
http·netty
ps酷教程20 天前
HttpPostRequestEncoder使用示例
http·netty
没有bug.的程序员22 天前
Java IO 与 NIO:从 BIO 阻塞陷阱到 NIO 万级并发
java·开发语言·nio·并发编程·io流·bio