首页>代码>使用netty实现文件列表下载的功能>/netty-download-file/src/main/java/com/example/demo/file/HttpFileServer.java
package com.example.demo.file; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponseEncoder; import io.netty.handler.stream.ChunkedWriteHandler; /** * 文件目录服务器启动类 * @author * @date 2019年11月20日 */ public class HttpFileServer { //文件访问目录,默认项目根目录 private static final String DEFAULT_URL = "/"; public void run(final int port, final String url) throws Exception { //创建线程组 EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { // 请求消息解码器 ch.pipeline().addLast("http-decoder", new HttpRequestDecoder()); // 目的是将多个消息转换为单一的request或者response对象 ch.pipeline().addLast("http-aggregator",new HttpObjectAggregator(65536)); // 响应消息解码器 ch.pipeline().addLast("http-encoder",new HttpResponseEncoder()); // 支持大文件传输 ch.pipeline().addLast("http-chunked",new ChunkedWriteHandler()); // 业务逻辑處理類 ch.pipeline().addLast("fileServerHandler",new HttpFileServerHandler(url)); } }); ChannelFuture future = b.bind(port).sync(); System.out.println("HTTP文件目录服务器启动,网址是 : " + "http://127.0.0.1:" + port + url); future.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { //优雅退出 bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { //启动文件目录服务器 new HttpFileServer().run(8080, DEFAULT_URL); } }


月光skr LV4
2023年5月13日
1302989672 LV3
2023年5月4日
youwuzuichen LV11
2022年11月8日
xuexizhuanyong23 LV16
2022年6月29日
liys1234 LV9
2022年4月27日
000000msj LV2
2022年3月28日
npc也有忧伤 LV3
2022年3月22日
雷迪斯俺的乡亲们 LV11
2022年3月9日
小新Coding LV9
2022年2月11日
xp95323 LV15
2022年1月25日