01.netty执行流程简述

netty执行流程简述

TestServer.java

package com.mzj.netty.ssy._01_simplehttp;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * netty服务端程序流程
 */
public class TestServer {

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

        //1.创建boss与worker线程组(事件循环组)
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        //2.创建服务器启动辅助类,服务端是 ServerBootstrap
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //3.设置childHandler的初始化器
            serverBootstrap.group(boss, worker).channel(NioServerSocketChannel.class).
                    childHandler(new TestServerInitiallzer());

            //5.绑定服务器端口并启动服务器,同步等待服务器启动完毕
            ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
            //6.阻塞启动线程,并同步等待服务器关闭,因为如果不阻塞启动线程,则会在finally块中执行优雅关闭,导致服务器也会被关闭了
            channelFuture.channel().closeFuture().sync();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }

    }
}
  1. 创建boss与worker事件循环线程组
  2. 创建服务器启动辅助类,服务端是 ServerBootstrap,客户端是Bootstrap
  3. 配置bootstrap:绑定线程组、设置channel、设置handler、设置childHandler(一般使用childHandler的初始化器-->handler的方式配置childHandler)
  4. 在初始化器的initChannel方法中添加各种handler,包括netty内置的+我们自定义的处理业务逻辑的handler
  5. 实现自定义的handler:通过实现netty在不同抽象父类handler中定义的回调方法,如下图,之后当特定的事件发生时,特定的回调方法被调用,根据事件处理对应的业务逻辑
  6. 绑定服务器端口并启动服务器,同步等待服务器启动完毕
  7. 阻塞启动线程,并同步等待服务器关闭,因为如果不阻塞启动线程,则会在finally块中执行优雅关闭,导致服务器也会被关闭了

TestServerInitiallzer.java

package com.mzj.netty.ssy._01_simplehttp;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;

public class TestServerInitiallzer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        //4.在初始化器的initChannel方法中添加各种handler,包括处理业务逻辑的自定义handler
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("httpServerCodec",new HttpServerCodec());
        pipeline.addLast("testHttpServerHandler",new TestHttpServerHandler());

    }
}

 

TestHttpServerHandler.java
package com.mzj.netty.ssy._01_simplehttp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        System.out.println(msg.getClass());
        System.out.println(ctx.channel().remoteAddress());

        if(msg instanceof HttpRequest){
            HttpRequest httpRequest = (HttpRequest) msg;

            System.out.println("请求方法名...:" + httpRequest.method().name());
            //过滤chrome等浏览器请求网站图标的请求
            URI uri = new URI(httpRequest.uri());
            if("/favicon.ico".equals(uri.getPath())){
                System.out.println("请求favicon.ico");
                return;
            }

            System.out.println("channelRead0执行了...");
            //模拟响应结果数据
            ByteBuf result = Unpooled.copiedBuffer("mazhongjia", CharsetUtil.UTF_8);

            //FullHttpResponse是netty提供的封装http响应的类
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,result);

            //设置http返回对象头信息
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,result.readableBytes());

            //返回response
            ctx.writeAndFlush(response);
            //模拟http请求/响应后,服务的关闭客户端连接
            //省略:判断http1.1或者1.0版本
            ctx.channel().close();
        }
    }

    /**
     * 客户端与服务端建立好连接时的回调函数
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerAdded.....");
        super.handlerAdded(ctx);
    }

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

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

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

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

完整代码:https://github.com/mazhongjia/nettyssynetty02/tree/master/src/main/java/com/mzj/netty/ssy/_01_simplehttp

或者https://gitee.com/mazhongjia/netty-ssy-netty/tree/master/src/main/java/com/mzj/netty/ssy/_01_simplehttp

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值