039_Netty网络编程服务端入门程序开发

java 复制代码
package com.ruyuan.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyServer {

    private int port;

    public NettyServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        // 肯定需要线程池,有的线程可以去负责跟大量的客户端建立网络连接
        // 有的线程可以去负责网络io数据读写
        // 网络io数据读取出来以后,处理请求数据,数据处理也需要专门的线程去处理
        EventLoopGroup bossGroup = new NioEventLoopGroup(); // 默认的线程池的大小,cpu core * 2
        EventLoopGroup workerGroup = new NioEventLoopGroup(20);

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                    .addLast(new StringDecoder())
                                    .addLast(new StringEncoder())
                                    .addLast(new NettyServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        System.out.println("starting netty server......");
        int port = 8998;
        if(args.length > 0) {
            port = Integer.parseInt(args[0]);
        }
        new NettyServer(port).start();
    }

}
java 复制代码
package com.ruyuan.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    // 网络连接tcp三次握手后,建立和封装一个channel,网络连接的通信管道
    // 此时这个channel应该就是可以实现一个激活
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel active......");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("channel read: " + (String)msg);

        String response = "hello world......";
        ByteBuf responseByteBuf = Unpooled.buffer();
        responseByteBuf.writeBytes(response.getBytes());

        ctx.channel().writeAndFlush(responseByteBuf);
        System.out.println("channel write: " + response);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel read complete......");
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();;
        ctx.close();
    }
}
相关推荐
浮尘笔记1 天前
Go语言临时对象池:sync.Pool的原理与使用
开发语言·后端·golang
梦梦代码精1 天前
BuildingAI vs Dify vs 扣子:三大开源智能体平台架构风格对比
开发语言·前端·数据库·后端·架构·开源·推荐算法
REDcker1 天前
RESTful API设计规范详解
服务器·后端·接口·api·restful·博客·后端开发
没有bug.的程序员1 天前
Java 序列化:Serializable vs. Protobuf 的性能与兼容性深度对比
java·开发语言·后端·反射·序列化·serializable·protobuf
我爱娃哈哈1 天前
SpringBoot + Spring Security + RBAC:企业级权限模型设计与动态菜单渲染实战
spring boot·后端·spring
小王不爱笑1321 天前
SpringBoot 配置文件
java·spring boot·后端
想用offer打牌1 天前
Spring AI vs Spring AI Alibaba
java·人工智能·后端·spring·系统架构
码农幻想梦1 天前
实验五 spring入门及IOC实验
java·后端·spring
a程序小傲1 天前
蚂蚁Java面试被问:向量数据库的相似度搜索和索引构建
开发语言·后端·python·架构·flask·fastapi
派大鑫wink1 天前
【Day39】Spring 核心注解:@Component、@Autowired、@Configuration 等
java·后端·spring