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!
相关推荐
beiback3 天前
Springboot + netty + rabbitmq + myBatis
spring boot·mysql·rabbitmq·mybatis·netty·java-rabbitmq
杨半仙儿还未成仙儿3 天前
java中IO遇NIO的区别,你需要了解
java·开发语言·nio
乌夷3 天前
NIO的callback调用方式
java·开发语言·nio
编程、小哥哥5 天前
netty之基础aio,bio,nio
android·nio
YISHEN源码6 天前
最新版ChatGPT对话系统源码 Chat Nio系统源码
人工智能·chatgpt·nio
Passion不晚6 天前
Java NIO 全面详解:掌握 `Path` 和 `Files` 的一切
java·后端·nio
林小果16 天前
NIO基础
java·网络·nio
DavidSoCool6 天前
java socket bio 改造为 netty nio
java·nio
智慧的牛8 天前
java NIO实现UDP通讯
java·udp·nio
山塘小鱼儿11 天前
Netty+HTML5+Canvas 网络画画板实时在线画画
java·前端·网络·netty·html5