Java based on socket file Transfer sample __java

Source: Internet
Author: User
Tags getmessage
The recent need for network transmission of large files, so the socket based on the file transfer made a preliminary understanding. On the basis of a user-provided program, I made some processing, using a buffer input/output flow to wrap the output stream, and then using data input/output flow packaging, speed of transmission. Less nonsense, first look at the server-side program.

1. Server-side

Package sterning;
Import Java.io.BufferedInputStream;
Import Java.io.DataInputStream;
Import Java.io.DataOutputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.net.ServerSocket;

Import Java.net.Socket;

    public class Servertest {int port = 8821;
        void Start () {Socket s = null;
            try {serversocket ss = new ServerSocket (port);
                while (true) {//Select file to be transmitted String FilePath = "D:\\lib.rar";

                File fi = new file (FilePath);

                System.out.println ("File Length:" + (int) fi.length ()); The public Socket accept () throws//IOException listens for and accepts connections to this socket.

                This method blocks until the connection is made.
                s = ss.accept ();
                SYSTEM.OUT.PRINTLN ("Establish socket link");
                DataInputStream dis = new DataInputStream (New Bufferedinputstream (S.getinputstream ()));

                Dis.readbyte (); DataInputStream fis = new DataInputStream (New BuFferedinputstream (New FileInputStream (FilePath));
                DataOutputStream PS = new DataOutputStream (S.getoutputstream ()); Pass the filename and length to the client.
                This is true for all platforms, such as the processing of Chinese names, as well as processing, which can be seen in the figure in Java 4th with ready-made code.
                Ps.writeutf (Fi.getname ());
                Ps.flush ();
                Ps.writelong ((Long) fi.length ());

                Ps.flush ();
                int buffersize = 8192;

                byte[] buf = new Byte[buffersize];
                    while (true) {int read = 0;
                    if (FIS!= null) {read = Fis.read (BUF);
                    } if (read = = 1) {break;
                } ps.write (buf, 0, read);
                } ps.flush ();                
                Note Close the socket link Oh, otherwise the client will wait for the server's data to come,//until the socket timeout, resulting in incomplete data.
                Fis.close ();                
  S.close ();              System.out.println ("File transfer complete");
        } catch (Exception e) {e.printstacktrace ();
    } public static void Main (String arg[]) {new Servertest (). Start ();
 }
}

2.socket Util Auxiliary class
Package sterning;
Import java.net.*;

Import java.io.*;

    public class Clientsocket {private String IP;

    private int port;

    Private socket socket = NULL;

    DataOutputStream out = null;

    DataInputStream getmessagestream = null;
        Public clientsocket (String IP, int port) {this.ip = IP;
    This.port = port; /** *//** * Create socket connection * * @throws Exception * Exception/public void C
        Reateconnection () throws Exception {try {socket = new socket (IP, port);
            catch (Exception e) {e.printstacktrace ();
            if (socket!= null) socket.close ();
        Throw e;
            The finally {}} public void SendMessage (String SendMessage) throws Exception {try {
            out = new DataOutputStream (Socket.getoutputstream ());
                if (Sendmessage.equals ("Windows")) {out.writebyte (0x1); Out. Flush ();
            Return
                } if (Sendmessage.equals ("Unix")) {out.writebyte (0x2);
                Out.flush ();
            Return
                } if (Sendmessage.equals ("Linux")) {out.writebyte (0x3);
            Out.flush ();
                else {Out.writeutf (SendMessage);
            Out.flush ();
            } catch (Exception e) {e.printstacktrace ();
            if (out!= null) out.close ();
        Throw e; The finally {}} public DataInputStream Getmessagestream () throws Exception {try {ge
            Tmessagestream = new DataInputStream (New Bufferedinputstream (Socket.getinputstream ()));
        return getmessagestream;
            catch (Exception e) {e.printstacktrace ();
            if (getmessagestream!= null) getmessagestream.close ();
        Throw e; } finally {}} public void Shutdownconnection () {try {if (out!= null) ou
            T.close ();
            if (getmessagestream!= null) getmessagestream.close ();
        if (socket!= null) socket.close ();
 The catch (Exception e) {}}}

3. Client
Package sterning;
Import Java.io.BufferedOutputStream;
Import Java.io.DataInputStream;
Import Java.io.DataOutputStream;

Import Java.io.FileOutputStream;

    public class Clienttest {private Clientsocket cs = null;

    Private String IP = "localhost";//set to server IP private int port = 8821;

    Private String SendMessage = "Windwos";
                Public clienttest () {try {if (CreateConnection ()) {SendMessage ();
            GetMessage ();
        } catch (Exception ex) {ex.printstacktrace ();
        } private Boolean createconnection () {cs = new Clientsocket (IP, port); try {cs.
            CreateConnection ();
            System.out.print ("Connect server succeeded!" + "\ n");
        return true;
            catch (Exception e) {System.out.print ("Connection Server failed!" + "\ n");
        return false;
        } private void SendMessage () {if (cs = null) return; try {
            Cs.sendmessage (SendMessage);
        catch (Exception e) {System.out.print ("Send message failed!" + "\ n");
        } private void GetMessage () {if (cs = null) return;
        DataInputStream inputstream = null;
        try {InputStream = Cs.getmessagestream ();
            catch (Exception e) {System.out.print ("receive message cache error \ n");
        Return
            A try {//local save path, and the file name is automatically inherited from the server side.
            String Savepath = "e:\\";
            int buffersize = 8192;
            byte[] buf = new Byte[buffersize];
            int passedlen = 0;
            
            Long len=0;
            Savepath + + Inputstream.readutf (); DataOutputStream fileout = new DataOutputStream (New Bufferedoutputstream (new
            FileOutputStream (Savepath)));
            
            Len = Inputstream.readlong ();
            System.out.println ("The length of the file is:" + len + "\ n"); System.out.println ("Start receiving files!" + "\ n");
                while (true) {int read = 0;
                if (InputStream!= null) {read = Inputstream.read (BUF);
                } Passedlen + = read;
                if (read = = 1) {break; //The following progress bar is done for the graphical interface of Prograssbar, here if the file is typed, it may be repeated to print out some of the same percentage System.out.println ("File Received" + (pas
                Sedlen * 100/len) + "%\n");
            Fileout.write (buf, 0, read);

            SYSTEM.OUT.PRINTLN ("Receive complete, File Save as" + Savepath + "\ n");
        Fileout.close ();
            catch (Exception e) {System.out.println ("Receive message error" + "\ n");
        Return
    } public static void Main (String arg[]) {new clienttest (); }
}

This enables the process of sending files from the server side to the client, and, of course, in turn, the same. Slightly different. The Cross-platform details are not implemented in the code, and sometimes friends who are interested can provide them.
Related Article

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.