Netty Http服务器可以配置要访问的资源和静态页资源

Netty Http服务器

是基于 netty 的 nio 简易 http 服务器

代码展示

public class HttpServer {
    Map<String, String> lastData = new HashMap<String, String>() {{
        put(".ico", "image/x-icon");
        put(".js", "text/javascript; charset=utf-8");
        put(".css", "text/css; charset=utf-8");
        put(".html", "text/html; charset=utf-8");
        put(".png", "image/png");
        put(".gif", "image/gif");
    }};

    {
        init();
    }

    public void init() {
        // 创建 group
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boosGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                    .addLast("Mine", new HttpServerCodec()) // 编码处理器
                                    .addLast("MineHandler", new SimpleChannelInboundHandler<HttpObject>() {
// Http 响应处理器
                                        @Override
                                        protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
                                            if (httpObject instanceof HttpRequest) {
                                                HttpRequest request = ((HttpRequest) httpObject);
                                                String baseUtl = "C:\\Users\\Administrator\\Desktop\\Company\\server";
                                                String uri = request.uri();
                                                // 对于默认的路径跳转做配置
                                                if (uri.equals("/")) uri = "/index.html";
                                                File file = new File(baseUtl + uri);
                                                // 访问指定文件的资源
                                                if (file.exists()) {
                                                    if (file.isDirectory()) {
                                                        sendMsg(channelHandlerContext, "文件数据拒绝访问");
                                                        return;
                                                    }
                                                    Lock lock = new ReentrantLock();
                                                    try (FileInputStream stream = new FileInputStream(file)) {
                                                        lock.lock();
                                                        if (file.length() > Integer.MAX_VALUE)
                                                            sendMsg(channelHandlerContext, "数据量太大");
                                                        byte[] b = new byte[(int) file.length()];
                                                        String type = uri.substring(uri.lastIndexOf("."));
                                                        while (true) {
                                                            int read = stream.read(b);
                                                            if (read == -1) break;
                                                            sendMsg(channelHandlerContext, b, type);
                                                        }
                                                    } catch (Exception e) {
                                                        System.err.println("发生未知异常 => " + e.getMessage());
                                                    } finally {
                                                        lock.unlock();
                                                    }
                                                } else {
                                                    System.err.println(uri + " => 数据不存在");
                                                    sendMsg(channelHandlerContext, "数据不存在");
                                                }
                                            }
                                        }
                                    });
                        }
                    });
            ChannelFuture future = serverBootstrap.bind(80).sync();
            System.out.println("服务器初始化成功");
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boosGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    /**
     * 返回客户端 404 消息 (也可以配置文件资源)
     *
     * @param channelHandlerContext 上下文
     * @param msg                   消息 {@link ByteBuf}
     */
    private void sendMsg(ChannelHandlerContext channelHandlerContext, String msg) {
        ByteBuf buffer = Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8);
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND, buffer
        );
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, getContentType(null));
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, buffer.readableBytes());
        channelHandlerContext.writeAndFlush(response);
    }

    /**
     * 发送消息给服务端
     *
     * @param channelHandlerContext 上下文
     * @param msg                   消息 {@link ByteBuf}
     * @param type                  处理的文件类型
     */
    private void sendMsg(ChannelHandlerContext channelHandlerContext, byte[] msg, String type) {
        ByteBuf buffer = Unpooled.copiedBuffer(msg);
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer
        );
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, getContentType(type));
        response.headers().set(HttpHeaderNames.ACCEPT_RANGES, "bytes");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, buffer.readableBytes());
        channelHandlerContext.writeAndFlush(response);
    }
    
    /**
     * 获取文件处理的对应的类型
     *
     * @param last 后缀
     */
    private String getContentType(String last) {
        String result = lastData.get(last);
        return ObjectUtils.isEmpty(result) ? "text/plain;charset=utf-8" : result;
    }

    public static void main(String[] args) {
        new HttpServer();
    }
}

**备注:**就可以通过http://127.0.0.1访问了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
是的,Netty可以创建HTTP请求服务器Netty是一个网络编程框架,可以处理各种协议,包括HTTP协议。使用Netty创建HTTP服务器非常简单,你只需要编写一个HTTP请求处理器并将其注册到Netty服务器的ChannelPipeline中即可。 下面是一个使用Netty创建HTTP服务器的简单示例: ```java public class HttpServer { public static void main(String[] args) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpServerCodec()); p.addLast(new HttpObjectAggregator(65536)); p.addLast(new HttpHandler()); } }) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(8080).sync(); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } private static class HttpHandler extends SimpleChannelInboundHandler<FullHttpRequest> { @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception { // 处理HTTP请求 String content = "Hello, World!"; FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(content.getBytes())); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain"); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes()); response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); ctx.write(response); ctx.flush(); } } } ``` 在上面的示例中,我们创建了一个HTTP服务器,并将其绑定到8080端口。当有HTTP请求到达时,Netty会将其转发给我们编写的HttpHandler处理器进行处理。HttpHandler处理器会返回一个"Hello, World!"的响应。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值