跟着官网学Netty

附上官网地址

Netty官网:https://netty.io/wiki/user-guide-for-4.x.html#wiki-h3-4

写一个Discard Server

跟着官方入门文档写一个比"hello,world"还简单的Netty服务端(收到请求后直接丢弃,hello-wordl都省了),边敲边理解。

public class DiscardServer {

    private int port;

    public DiscardServer(int port) {
        this.port = port;
    }
    public void run() throws Exception {
        //接收连接
        EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
        //处理boss接收并且register到当前worker的连接
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //帮助类,启动Server
            ServerBootstrap b = new ServerBootstrap(); // (2)
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class) // (3)即将被实例化的ServerChannel,接收连接的类
                    .childHandler(new ChannelInitializer<SocketChannel>() { // (4)通过给pipeline增加handler来配置Channel的处理逻辑
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new DiscardServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)          // (5)ServerChannel相关参数
                    .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)被ServerChannel接收的Channel的相关参数
            //bind()方法会create a new channel and bind it
            //sync()方法会阻塞到future完成,如果失败了会抛出异常
            ChannelFuture f = b.bind(port).sync(); // (7)绑定端口,开始接收连接

            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        }

        new DiscardServer(port).run();
    }
}

一个简单的Handler

收到请求后,直接释放

public class DiscardServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ((ByteBuf) msg).release();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值