一個(gè)簡單的Netty Demo

netty

  • ChannelFuture ChannelFuture的作用是用來保存Channel異步操作的結(jié)果。
  • ChannelPipeline : 可以看做是ChannelHandler的鏈表,用來添加不同的ChannelHandler

nettydemo:

public class TestServer {
    private static final int port = 10000;

    public static void main(String[] args) throws InterruptedException {

        //看做一個(gè)死循環(huán),程序永遠(yuǎn)保持運(yùn)行
        EventLoopGroup bossGroup = new NioEventLoopGroup(); //完成線程的接收,將連接發(fā)送給worker
        EventLoopGroup workerGroup = new NioEventLoopGroup(); //完成連接的處理
        try {
            //對(duì)于相關(guān)啟動(dòng)信息進(jìn)行封裝
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap
                    .group(bossGroup, workerGroup) //注入兩個(gè)group
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new TestServerInitializer());

            //綁定端口對(duì)端口進(jìn)行監(jiān)聽,啟動(dòng)服務(wù)器
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

Initializer:

public class TestServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        //類似于一個(gè)攔截器鏈
        ChannelPipeline pipeline = ch.pipeline();

        pipeline.addLast("httpServerCodec", new HttpServerCodec()); //對(duì)于web請(qǐng)求進(jìn)行編解碼作用
        pipeline.addLast("testHttpServerHandler", new TestHttpServerHandler());

    }
}

自定義處理器ServerHandler(用作邏輯處理)

public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    //讀取客戶端發(fā)過來的請(qǐng)求,并且向客戶端響應(yīng)
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpRequest) {
            HttpRequest httpRequest = (HttpRequest) msg;

            //設(shè)置響應(yīng)內(nèi)容,以及響應(yīng)編碼格式
            ByteBuf content = Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8);
            //指定http協(xié)議,響應(yīng)狀態(tài)碼,響應(yīng)內(nèi)容
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain"); //設(shè)置響應(yīng)類型
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes()); //設(shè)置響應(yīng)字節(jié)長度

            //將內(nèi)容返回到客戶端
            ctx.writeAndFlush(response);
            ctx.channel().close(); //關(guān)閉連接
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel active");
        super.channelActive(ctx);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel registered");
        super.channelRegistered(ctx);
    }


    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handler added");
        super.handlerAdded(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel inactive");
        super.channelInactive(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel unregister");
        super.channelUnregistered(ctx);
    }

}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容