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 小时前
1、Elasticsearch快照迁移
后端
sin601 小时前
学习笔记:异常,泛型,集合(代码示例,企业面试题,企业实际应用场景)
后端
小安同学iter1 小时前
天机学堂day05
java·开发语言·spring boot·分布式·后端·spring cloud·微服务
无限进步_2 小时前
C语言宏的魔法:探索offsetof与位交换的奇妙世界
c语言·开发语言·windows·后端·算法·visual studio
白露与泡影2 小时前
springboot中File默认路径
java·spring boot·后端
汝生淮南吾在北2 小时前
SpringBoot+Vue游戏攻略网站
前端·vue.js·spring boot·后端·游戏·毕业设计·毕设
IMPYLH2 小时前
Lua 的 type 函数
开发语言·笔记·后端·junit·lua
ConardLi3 小时前
分析了 100 万亿 Token 后,得出的几个关于 AI 的真相
前端·人工智能·后端
老华带你飞3 小时前
英语学习|基于Java英语学习系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端·学习