netty实现http服务器

简介: 1. HttpServerHttpServer作为http服务器的server端:public final class HttpServer { private static final String IP = "127.

1. HttpServer

HttpServer作为http服务器的server端:

public final class HttpServer {

    private static final String IP = "127.0.0.1";
    private static final int PORT = 9000;
    private static final int BIZ_THREAD_SIZE = 100;

    private static final Logger logger = LoggerFactory.getLogger(HttpServer.class);

    public static void main(String[] args) throws Exception {
        System.out.println("启动Server...");
        HttpServer.start();
    }

    public static void start() throws Exception {
        initServerConfig();

        // new NioEventLoopGroup()默认线程数为CPU核心数的两倍(Runtime.getRuntime().availableProcessors() * 2),所以这里不用额外指定。
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        // 这里worker不能使用默认,如果并发大的话需要增加线程数量
        EventLoopGroup workerGroup = new NioEventLoopGroup(BIZ_THREAD_SIZE);

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    // ChannelOption.SO_BACKLOG对应的是tcp/ip协议listen函数中的backlog参数。函数listen(int socketfd, int backlog)用来初始化服务端可连接队列。
                    // 服务端处理客户端连接请求是顺序处理的,所以同一时间只能处理一个客户端连接,多个客户端来的时候,服务端将不能处理的客户端连接请求放在队列中等待处理,backlog参数指定了队列的大小。
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childOption(ChannelOption.SO_KEEPALIVE, true) // 子channel配置,保持长连接
                    .childHandler(new HttpServerInitializer());

            // sync追踪代码可以得到:this.await(),实现阻塞
            ChannelFuture channelFuture = bootstrap.bind(IP, PORT).sync();

            // 启动失败则关闭线程组
            if (!channelFuture.isSuccess()) {
                shutdown(bossGroup, workerGroup);
                throw new RuntimeException(channelFuture.cause());
            }

            channelFuture.channel().closeFuture().sync();
            logger.info("bootstrap channel closed...");
        } finally {
            shutdown(bossGroup, workerGroup);
        }
    }

    // 添加路径映射和过滤器映射
    private static void initServerConfig() {
        ServerContext.setFilter(ServerContext.MAPPING_ALL, BaseFilter.class);
        ServerContext.setFilter("/template", TemplateFilter.class);
        ServerContext.setAction(ServerContext.MAPPING_ALL, DefaultIndexAction.class);
        ServerContext.setAction("/template", TemplateAction.class);
        ServerContext.setAction("/files", FileAction.class);
        ServerContext.setROOT("root");
        ServerContext.setPORT(8090);
    }

    private static void shutdown(EventLoopGroup bossGroup, EventLoopGroup workerGroup) {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
AI 代码解读

HttpServerInitializer设置http编解码器,以及请求aggregator等:

public class HttpServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    public void initChannel(SocketChannel socketChannel) {
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline
                //或者使用HttpRequestDecoder & HttpResponseEncoder
                .addLast(new HttpServerCodec())
                //把HttpObjectAggregator放入管道里。HttpObjectAggregator会把多个消息转换为一个单一的FullHttpRequest或是FullHttpResponse
                .addLast(new HttpObjectAggregator(1024 * 1024))
                //压缩Http消息
//                            .addLast(new HttpChunkContentCompressor())
                //大文件支持,文件上传时使用
//                            .addLast(new ChunkedWriteHandler())
                .addLast(new HttpServerExpectContinueHandler())
                .addLast(new HttpServerDispatcherHandler());
    }
}
AI 代码解读

入栈处理器,用于转发http请求,类似于DispatcherServlet:

public class HttpServerDispatcherHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (!(msg instanceof FullHttpRequest)) {
            return;
        }

        FullHttpRequest fullHttpRequest = (FullHttpRequest) msg;
        final Request customerRequest = Request.build(ctx, fullHttpRequest);
        final Response customerResponse = Response.build(ctx, customerRequest);
        if (customerRequest.getRequestUrl().equals(HttpHelper.FAVICON_ICO)) {
            return;
        }

        // 过滤器放行之后,执行action,实际处理业务逻辑
        boolean passFilter = doFilter(customerRequest, customerResponse);
        if (passFilter) {
            doAction(customerRequest, customerResponse);
        }

        //如果发送请求未被触发,则触发之,否则跳过。
        if(false == customerResponse.isSent()) {
            customerResponse.response();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    /**
     * 过滤器
     * @param request
     * @param response
     * @return
     */
    private boolean doFilter(Request request, Response response) {
        //全局过滤器
        Filter filter = ServerContext.getFilter(ServerContext.MAPPING_ALL);
        if(null != filter) {
            if(false == filter.doFilter(request, response)) {
                return false;
            }
        }

        //自定义过滤器
        filter = ServerContext.getFilter(request.getRequestUrl());
        if(null != filter) {
            if(false == filter.doFilter(request, response)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 请求处理器
     * 相当于servlet
     * @param request
     * @param response
     */
    private void doAction(Request request, Response response) {
        Action action = ServerContext.getAction(request.getRequestUrl());
        if (null == action) {
            //查找匹配所有路径的Action
            action = ServerContext.getAction(ServerContext.MAPPING_ALL);
            if(null == action) {
                // 非Action方法,调用静态文件读取
                action = Singleton.get(FileAction.class);
            }
        }

        action.doAction(request, response);
    }
}
AI 代码解读

过滤器

public interface Filter {
    
    /**
     * 执行过滤
     * @param request 请求对象
     * @param response 响应对象
     * @return 如果返回true,则继续执行下一步内容,否则中断
     */
    boolean doFilter(Request request, Response response);
}
AI 代码解读

过滤器示例:

public class TemplateFilter implements Filter {

    @Override
    public boolean doFilter(Request request, Response response) {
        System.out.println("welcome in template filter...");
        return true;
    }
}
AI 代码解读

action

action用于实际处理业务,顶层接口:

public interface Action {

    void doAction(Request request, Response response);
}
AI 代码解读

抽象Adapter:

public abstract class AbstractAction implements Action {

    @Override
    public void doAction(Request request, Response response) {
        String method = request.getMethod();
        if (HttpHelper.METHOD_GET.equals(method)) {
            doGet(request, response);
        } else if (HttpHelper.METHOD_POST.equals(method)) {
            doPost(request, response);
        } else if (HttpHelper.METHOD_PUT.equals(method)) {
            doPut(request, response);
        } else if (HttpHelper.METHOD_DELETE.equals(method)) {
            doDelete(request, response);
        } else if (HttpHelper.METHOD_HEAD.equals(method)) {
            doHead(request, response);
        } else if (HttpHelper.METHOD_OPTIONS.equals(method)) {
            doOptions(request, response);
        } else if (HttpHelper.METHOD_TRACE.equals(method)) {
            doTrace(request, response);
        }
    }

    protected void doGet(Request request, Response response) {}

    protected void doPost(Request request, Response response) {}

    protected void doPut(Request request, Response response) {}

    protected void doDelete(Request request, Response response) {}

    protected void doOptions(Request request, Response response) {}

    protected void doHead(Request request, Response response) {}

    protected void doTrace(Request request, Response response) {}
}
AI 代码解读

action示例:

public class TemplateAction extends AbstractAction {

    @Override
    protected void doGet(Request request, Response response) {
        response.setContentType(HttpHelper.CONTENT_TYPE_JSON);
        response.setContent("welcome in template action, do get...");
    }

    @Override
    protected void doPost(Request request, Response response) {
        response.setContent("welcome in template action, do post...");
    }
}
AI 代码解读

。。。

目录
打赏
0
0
0
0
297
分享
相关文章
|
7天前
|
使用Python实现multipart/form-data文件接收的http服务器
至此,使用Python实现一个可以接收 'multipart/form-data' 文件的HTTP服务器的步骤就讲解完毕了。希望通过我的讲解,你可以更好地理解其中的逻辑,另外,你也可以尝试在实际项目中运用这方面的知识。
99 69
网络通讯技术:HTTP POST协议用于发送本地压缩数据到服务器的方案。
总的来说,无论你是一名网络开发者,还是普通的IT工作人员,理解并掌握POST方法的运用是非常有价值的。它就像一艘快速,稳定,安全的大船,始终为我们在网络海洋中的冒险提供了可靠的支持。
51 22
HTTP代理服务器对速度提升有何作用?
在信息化时代,网络成为生活不可或缺的一部分。HTTP代理服务器位于客户端与服务器之间,通过数据压缩、缓存机制和路由优化等方式,有效提高数据传输速度并保护个人信息安全。使用91HTTP等工具,用户可在业务需求中获得更快更安全的网络体验。
52 4
解析HTTP代理服务器不稳定致使掉线的关键原因
随着数字化发展,网络安全和隐私保护成为核心需求。HTTP代理服务器掉线原因主要包括:1. 网络问题,如本地网络不稳定、路由复杂;2. 服务器质量差、IP资源不稳定;3. 用户配置错误、超时或请求频率异常;4. IP失效或协议不兼容。这些问题会影响连接稳定性。
110 8
HTTP代理服务器在网络安全中的重要性
随着科技和互联网的发展,HTTP代理IP中的代理服务器在企业业务中扮演重要角色。其主要作用包括:保护用户信息、访问控制、缓存内容、负载均衡、日志记录和协议转换,从而在网络管理、性能优化和安全性方面发挥关键作用。
131 2
探索网络模型与协议:从OSI到HTTPs的原理解析
OSI七层网络模型和TCP/IP四层模型是理解和设计计算机网络的框架。OSI模型包括物理层、数据链路层、网络层、传输层、会话层、表示层和应用层,而TCP/IP模型则简化为链路层、网络层、传输层和 HTTPS协议基于HTTP并通过TLS/SSL加密数据,确保安全传输。其连接过程涉及TCP三次握手、SSL证书验证、对称密钥交换等步骤,以保障通信的安全性和完整性。数字信封技术使用非对称加密和数字证书确保数据的机密性和身份认证。 浏览器通过Https访问网站的过程包括输入网址、DNS解析、建立TCP连接、发送HTTPS请求、接收响应、验证证书和解析网页内容等步骤,确保用户与服务器之间的安全通信。
277 3
HTTPS协议是**一种通过计算机网络进行安全通信的传输协议
HTTPS协议是**一种通过计算机网络进行安全通信的传输协议
115 11
HTTPS协议的历史发展
HTTPS协议的历史发展
156 8
判断一个网站是否使用HTTPS协议
判断一个网站是否使用HTTPS协议
676 4

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等