Netty 实战:如何实现文件服务器?

文件服务器实现一个可以展示指定用户输入的文件路径,返回对应文件内容的服务器 。

Netty 实战:如何实现文件服务器?

文章插图
 
实例代码服务端public class FileServer {    public static void main(String[] args) {        EventLoopGroup bossGroup = new NioEventLoopGroup();        EventLoopGroup workerGroup = new NioEventLoopGroup();        try {            ServerBootstrap serverBootstrap = new ServerBootstrap();            ChannelFuture channelFuture = serverBootstrap.group(bossGroup, workerGroup)                    .channel(NIOServerSocketChannel.class)                    .childHandler(new ChannelInitializer<SocketChannel>() {                        @Override                        protected void initChannel(SocketChannel ch) throws Exception {                            // 编码 String                            ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8))                                    // 按照行进行解码                                    .addLast(new LineBasedFrameDecoder(1024))                                    // String 解码                                    .addLast(new StringDecoder(CharsetUtil.UTF_8))                                    // 大数据流的处理                                    .addLast(new ChunkedWriteHandler())                                    .addLast(new FileServerHandler());                        }                    })                    .bind(8889)                    .syncUninterruptibly();            channelFuture.channel().closeFuture().syncUninterruptibly();        } finally {            workerGroup.shutdownGracefully();            bossGroup.shutdownGracefully();        }    }}FileServerHandler.JAVA针对文件服务器的处理,实现如下:
import java.io.RandomaccessFile;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import io.netty.handler.stream.ChunkedFile;public class FileServerHandler extends SimpleChannelInboundHandler<String> {    @Override    public void channelActive(ChannelHandlerContext ctx) throws Exception {        // 提醒客户端输入文件路径        ctx.writeAndFlush("HELLO: Type the path of the file to retrieve.n");    }    @Override    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {        // 只读方式打开文件        try(RandomAccessFile file = new RandomAccessFile(msg, "r")) {            long length = file.length();            ctx.write("OK: " + length + 'n');            ctx.write(new ChunkedFile(file));            ctx.writeAndFlush("n");        }    }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {        cause.printStackTrace();        ctx.close();    }}


推荐阅读