Netty权威指南之文件传输

哈哈 阅读:732 2021-03-31 22:28:07 评论:0

本章相关知识点:

文件是最常见的数据源之一,在程序经常需要将数据存储到文件中,比如:图片文件、声音文件等数据文件。在实际使用中,文件都包含一个特定的格式,这个格式需要程序员根据需求进行设计。读取已有文件是需要熟悉对应文件格式,才能把数据从文件中正确的读取出来。

在NIO类库提供之前,Java所以的文件操作分为两大类:

1、基于字节流的InputStream和OutputStram;

2、基于字符流的Reader和Writer;

通过NIO新提供的FileChannel类库可以方便地以“管道”方式对文件进行各种I/O操作,相比于传统以流方式进行的I/O操作有了很大的变化和改进。


本章主要学习目标

1、文件的基础知识

2、Netty文件传输开发

3、运行Netty 文件传输项目;


第一节:文件的基础知识

可以参考下面这边文章:


第二节:Netty文件传输开发

服务端源代码:

FileServer.java

package com.nio.file; 
 
import io.netty.bootstrap.ServerBootstrap; 
import io.netty.channel.ChannelFuture; 
import io.netty.channel.ChannelInitializer; 
import io.netty.channel.ChannelOption; 
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.LineBasedFrameDecoder; 
import io.netty.handler.codec.string.StringDecoder; 
import io.netty.handler.codec.string.StringEncoder; 
import io.netty.util.CharsetUtil; 
 
/** 
 * Created by vixuan-008 on 2015/6/25. 
 */ 
public class FileServer { 
    public void run(int port) throws Exception { 
        EventLoopGroup bossGroup = new NioEventLoopGroup(); 
        EventLoopGroup workerGroup = new NioEventLoopGroup(); 
        try { 
            ServerBootstrap b = new ServerBootstrap(); 
            b.group(bossGroup, workerGroup) 
                    .channel(NioServerSocketChannel.class) 
                    .option(ChannelOption.SO_BACKLOG, 100) 
                    .childHandler(new ChannelInitializer<SocketChannel>() { 
                        /* 
                         * (non-Javadoc) 
                         * 
                         * @see 
                         * io.netty.channel.ChannelInitializer#initChannel(io 
                         * .netty.channel.Channel) 
                         */ 
                        public void initChannel(SocketChannel ch) 
                                throws Exception { 
                            ch.pipeline().addLast( 
                                    new StringEncoder(CharsetUtil.UTF_8), 
                                    new LineBasedFrameDecoder(1024), 
                                    new StringDecoder(CharsetUtil.UTF_8), 
                                    new FileServerHandler()); 
                        } 
                    }); 
            ChannelFuture f = b.bind(port).sync(); 
            System.out.println("Start file server at port : " + port); 
            f.channel().closeFuture().sync(); 
        } finally { 
            // 优雅停机 
            bossGroup.shutdownGracefully(); 
            workerGroup.shutdownGracefully(); 
        } 
    } 
 
    public static void main(String[] args) throws Exception { 
        int port = 17887; 
        new FileServer().run(port); 
    } 
} 

FileServerHandler.java

package com.nio.file; 
 
import io.netty.channel.ChannelHandlerContext; 
import io.netty.channel.DefaultFileRegion; 
import io.netty.channel.FileRegion; 
import io.netty.channel.SimpleChannelInboundHandler; 
 
import java.io.File; 
import java.io.RandomAccessFile; 
 
/** 
 * Created by vixuan-008 on 2015/6/25. 
 */ 
public class FileServerHandler extends SimpleChannelInboundHandler<String> { 
    private static final String CR = System.getProperty("line.separator"); 
 
    /* 
     * (non-Javadoc) 
     * 
     * @see 
     * io.netty.channel.SimpleChannelInboundHandler#messageReceived(io.netty 
     * .channel.ChannelHandlerContext, java.lang.Object) 
     */ 
    public void messageReceived(ChannelHandlerContext ctx, String msg) 
            throws Exception { 
        File file = new File(msg); 
        if (file.exists()) { 
            if (!file.isFile()) { 
                ctx.writeAndFlush("Not a file : " + file + CR); 
                return; 
            } 
            ctx.write(file + " " + file.length() + CR); 
            RandomAccessFile randomAccessFile = new RandomAccessFile(msg, "r"); 
            FileRegion region = new DefaultFileRegion( 
                    randomAccessFile.getChannel(), 0, randomAccessFile.length()); 
            ctx.write(region); 
            ctx.writeAndFlush(CR); 
            randomAccessFile.close(); 
        } else { 
            ctx.writeAndFlush("File not found: " + file + CR); 
        } 
    } 
 
    /* 
     * (non-Javadoc) 
     * 
     * @see 
     * io.netty.channel.ChannelHandlerAdapter#exceptionCaught(io.netty.channel 
     * .ChannelHandlerContext, java.lang.Throwable) 
     */ 
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) 
            throws Exception { 
        ctx.close(); 
    } 
} 

第三节:运行Netty 文件传输项目

启动文件服务器,打开CMD控制台,通过telnet命令连接到主机,如图所示:


连接成功后,输入需要传输的文件路径:D:\network.xml,然后输入回车键,显示结果如图所示:




声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号