Netty学习之服务端基础概念(二)

 服务端基本代码流程

客户端流程去掉一个用来监听接受客户端请求的bossGroup事件循环组启动类也去掉对应的Sever用Bootstrap对象去实现

public class TestServer {
    public static void main(String[] args) throws Exception {
        //创建两个事件循环组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //创建一个服务端启动对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //将事件循环组和自己实现的通道初始化器添加到启动对象中
            serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new TestServerInitializer());
            //监听端口
            ChannelFuture ch = serverBootstrap.bind(8083).sync();
            ch.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}


public class TestServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    //建立连接后会调用初始化器的初始化方法
    protected void initChannel(SocketChannel ch) throws Exception {
        //给通道添加对应的编解码器
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("httpServerCodec",new HttpServerCodec());
        //添加自己实现的额编解码器
        pipeline.addLast("testHttpServerHandler",new TestServerHttpHandler());
    }
}

public class TestServerHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        ByteBuf content = Unpooled.copiedBuffer("Hello World!",CharsetUtil.UTF_8);
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,content);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());
        ctx.writeAndFlush(response);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值