Java Simple TCP File transfer

Source: Internet
Author: User

Service Side
 PackageTCP;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;Importjava.net.InetSocketAddress;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public classTcp_file_server { Public Static voidMain (string[] args)throwsException {/*** Create service End sockets*/ServerSocket SS=NewServerSocket (); /*** Bind specified port*/Ss.bind (NewInetsocketaddress (12345)); System.out.println ("" The network disk begins to run ""); /*** Listen and accept the client socket connection and return a socket*/                /*** Continue to receive the information sent by the client and give it to the thread processing*/         while(true) {Socket Socket=ss.accept (); NewThread (NewUpLoad (socket)). Start (); }    }}classUpLoadImplementsrunnable{PrivateSocket socket =NULL;  PublicUpLoad (socket socket) { This. Socket =socket; } @Override Public voidrun () {OutputStream out=NULL; Try {            //Create a file input stream to receive the file stream in the client's socketInputStream in =Socket.getinputstream (); /*** Get filename length * file format: File name Length (number) \r\ file name \ r \ n file contents \ r \ n * Get file name-read the length of the file name before the first carriage return line and read The length of the byte is the file name * Read data until the first carriage return is encountered * Every time you read a byte from the stream into a string to put it on line as long as line is not \ r \ n The end repeats the process /c2>*/String line1= ""; byte[] By1 =New byte[1];  while(!line1.endswith ("\ r \ n") {in.read (by1); String Str=NewString (by1); Line1+=str; }            /*** 1. Read length, minus \ r \ n is the length of the file name * 2.PARSEINT (): The function is to convert the parsed string into an integer.             * 3.substring (): Returns a new string that is a substring of this string. */            intLen1 = Integer.parseint (line1.substring (0, Line1.length ()-2)); /*** 1. Read file name * 2. Create a byte array of equal length and file name to hold the file name * 3.read (data): reads a certain number of bytes from the input stream and stores it in a buffered The data array in the area array data, how much content is read in the in input stream, and the contents are stored in the data array*/            byte[] data =New byte[LEN1];            In.read (data); String FileName=NewString (data); //get file content byte lengthString line2 = ""; byte[] By2 =New byte[1];  while(!line2.endswith ("\ r \ n") {in.read (by2); String Str=NewString (BY2); Line2+=str; }            intLen2 = Integer.parseint (line2.substring (0, Line2.length ()-2)); //Create the output stream of the input file, specify the file export addressString Path = "e:/" +FileName; out=NewFileOutputStream (path); //get file Content bytes//Flow Docking            byte[] By3 =New byte[Len2];            In.read (BY3);                        Out.write (BY3); System.out.println ("Receive from" +socket.getinetaddress (). Gethostaddress () + "uploaded file" +path); } Catch(IOException e) {e.printstacktrace (); }finally {            //Close Resource//turn off the output stream            Try {                if(Out! =NULL) {out.close (); }            } Catch(IOException e) {e.printstacktrace (); }finally{ out=NULL; }            //Close Socket            Try {                if(Socket! =NULL) {socket.close (); }            } Catch(IOException e) {e.printstacktrace (); }finally{Socket=NULL; }        }    }}
Client
 PackageTCP;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;Importjava.net.InetSocketAddress;ImportJava.net.Socket;ImportJava.util.Scanner; Public classtcp_file_client { Public Static voidMain (string[] args) {Scanner scan=NULL; InputStream in=NULL; Socket Socket=NULL; Try {            /*** 1. Scan console Receive File pathname * Create a file reference, point to a new file object, and give the address*/System.out.println ("Please enter the path of the file to be transferred:"); Scan=NewScanner (system.in); String Path=Scan.nextline (); File File=NewFile (path); /*** 2. Determine if the file is a text file instead of a folder and the path exists * EXISTS (): Determine if the file exists * Isfile (): Determine if the file is /c7>*/            if(File.exists () &&File.isfile ()) {                                /*** 3. Create a file input stream, send a file * The contents of the file input are placed in the files*/inch=Newfileinputstream (file); /*** Socket This class implements a client socket (also known as a "socket").                 Sockets are the endpoints of communication between two machines. * 4. Create a client socket*/Socket=NewSocket (); //inetsocketaddress inets = new Inetsocketaddress ("127.0.0.1", 12345);                                /*** 5. Connect the TCP server * determine the IP and port number on the service side*/Socket.connect (NewInetsocketaddress ("127.0.0.1", 12345)); /*** 6. Get the output stream to the client * OutputStream getoutputstream () *                  Returns the output stream for this socket. */OutputStream out=Socket.getoutputstream (); /*** 7. Send a file to the server * itself defines a protocol to solve the sticky packet phenomenon, get the file name * 7.1. We first read the contents of the file and put it                 Inside * 7.2. Read the file name File.getname () * 7.3. Convert the file name to Byte File.getname (). GetBytes ()                 * 7.4. Gets the length of the byte of the file name File.getname (). GetBytes (). length * 7.5. Add \ r \ n as an identifier after the filename length */                //Send to server [filename byte length \ r \ n]Out.write ((File.getname (). GetBytes (). length + "\ r \ n"). GetBytes ()); //Send to server [filename bytes]Out.write (File.getname (). GetBytes ()); //Send to server [file byte length \ r \ n]Out.write ((file.length () + "\ r \ n"). GetBytes ()); //send [File byte contents] to server                byte[] data =New byte[1024]; inti = 0;  while((i = in.read (data))! =-1) {out.write (data,0, i); }                            }Else{System.out.println ("File does not exist or a file ~ ~"); }        } Catch(Exception e) {e.printstacktrace (); }finally {            /*** Turn off scanner, file input stream, socket * Socket to decorate the output stream, so do not close the output stream*/            if(Scan! =NULL) {scan.close (); }            Try {                if(In! =NULL) {in.close (); }            } Catch(IOException e) {e.printstacktrace (); }finally {                //force the input stream to be emptyin =NULL; }            Try {                if(Socket! =NULL) {socket.close (); }            } Catch(IOException e) {e.printstacktrace (); }finally {                //Force release SocketSocket =NULL; }} System.out.println ("File Transfer Complete"); }}

Java Simple TCP File transfer

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.