Netty Authority Guide File transfer

Source: Internet
Author: User
Tags throwable

Relevant knowledge points in this chapter:

Files are one of the most common data sources, where programs often need to store data in a file, such as a picture file, a sound file, and other data files. In practice, files contain a specific format that requires programmers to design on demand. Reading an existing file requires familiarity with the corresponding file format in order to read the data correctly from the file.

Before the NIO class library is available, Java's file operations fall into two broad categories:

1, InputStream and Outputstram based on the byte stream;

2. Reader and writer based on character streams;

The new FileChannel class library provided by NiO makes it easy to do various I/O operations on the file in a "pipe" manner, which has greatly changed and improved compared to the traditional streaming I/O operations.


Main learning objectives of this chapter

1, the basic knowledge of the document

2, Netty File transfer development

3, the operation of Netty file transfer project;


Section I: Basic knowledge of documents

You can refer to the following article:


Section II: Netty File Transfer Development

Service-Side Source code:

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 Nioev
        Entloopgroup ();
        Eventloopgroup Workergroup = new Nioeventloopgroup ();
            try {serverbootstrap b = new Serverbootstrap ();
            B.group (Bossgroup, Workergroup). Channel (Nioserversocketchannel.class)        . option (Channeloption.so_backlog). Childhandler (New CHANNELINITIALIZER<SOCKETCHANNEL&G
                         t; () {* * * (NON-JAVADOC) * * @see * Io.netty.channel.channelinitializer#initchannel (IO *. nett
                                Y.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 Fileserverhandle
                        R ());
            }
                    });
            Channelfuture f = b.bind (port). sync (); System.out.println ("Start F")Ile Server at Port: "+ port";
        F.channel (). Closefuture (). sync ();
            finally {//graceful downtime 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.N Etty.channel *. Channelhandlercontext, java.lang.Throwable) */public void Exceptioncaught (Channelhandlercontext ctx, Throwable C
    Ause) throws Exception {ctx.close ();
 }
}

Section III: Running the Netty File transfer project

Start the file server, open the CMD console, and connect to the host by Telnet command, as shown in the figure:


When the connection is successful, enter the file path you want to transfer: D:\network.xml, and then enter the return key, showing the results as shown in the figure:




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.