Java implements a client's operation to send a file to the server

Source: Internet
Author: User
Tags sendfile file transfer protocol

Server Source code:
Import Java.io.bufferedreader;import Java.io.file;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.io.InputStreamReader; Import Java.net.serversocket;import java.net.socket;/** * * File name: Serverreceive.java * Implementation function: As the server receives the files sent by the client * * Specific implementation process: * 1, the establishment of Socketserver, waiting for the client's connection * 2, when there is a client connection, in accordance with the Agreement between the parties, at this time to read a row of data * where the client to send the file name and size information * 3, according to the file name in the local creation of files, and establish a good flow of letters * 4, Loop receive packet, write the packet to file * 5, when the length of the received data is equal to the length of the file sent in advance file, that is, the file received, close the file * 6, the end of the File receive work * * * NOTE: This code only for the demo client and server transfer file use, * each packet before the file protocol life * Specific protocol transmission and the use of files out of the stage can be placed on their own program to place the "* * * * * * * * * * * * * * * * Created: 2014-08-19 * * */public class Serverreceive {public static void Mai N (string[] args) {/** A communication handle to the server to establish a connection */serversocket SS = null; Socket s = null;/** defines the file object and file output stream object that is used to create the locally created after the receive */file file = null; FileOutputStream fos = null;/** defines the input stream, uses the socket's inputstream to input the packet */inputstream is = null;/** defines a byte array to be the packet's storage packet */ byte[] buffer = new byte[4096 * 5];/** used to receive file send request string */string Comm = null;/** Build SOcekt communication, waiting for the server to connect */try {ss = new ServerSocket (4004); s = ss.accept ();} catch (IOException e) {e.printstacktrace ();} /** reads the contract information sent over a line of clients */try {InputStreamReader ISR = new InputStreamReader (S.getinputstream ()); BufferedReader br = new BufferedReader (ISR); comm = Br.readline ();} catch (IOException e) {System.out.println ("Server Disconnected from client");} /** begins parsing the request command sent by the client */int index = comm.indexof ("/#"),/** determines whether the protocol is the Protocol to send the file */string xieyi = comm.substring (0, index); Xieyi.equals ("111")) {System.out.println ("the server received an incorrect protocol code"); return;} /** parse out the file name and size */comm = comm.substring (index + 2); index = Comm.indexof ("/#"); String filename = comm.substring (0, index). Trim (); String filesize = comm.substring (index + 2). Trim ();/** create an empty file to receive the file */file = new file (filename); if (!file.exists ()) {try {File.createnewfile ();} catch (IOException e) {System.out.println ("server-side Create file failed");}} else{/** can also ask whether to overwrite */system.out.println ("This path already exists the same file, overwrite");} /** "Above is the preparation portion of the server that is written in the client code" *//** * server receives the key code of the file */try {/** wraps the file into the file output stream object */fos = new FileOutputStream (file); Long file_size = Long.parselong (filesize), is = S.getinputstream (),/**size is the length of each receive packet */int size = 0;/** Count is used to record the length of the received file */long count = 0;/** uses the while loop to receive the packet */while (Count < file_size) {/** reads a packet from the input stream */size = Is.read ( buffer);/** writes the packet just read to the local file */fos.write (buffer, 0, size), Fos.flush ();/** will have received the length of the file +size*/count + = size; SYSTEM.OUT.PRINTLN ("Server-side received packet, size" + size);}} catch (FileNotFoundException e) {System.out.println ("Server write file Failed"),} catch (IOException e) {System.out.println (" Server: Client disconnects "); finally{/** * Close Open File * If required, you can also close the socket connection * */try {if (fos! = null) Fos.close (),} catch (IOException e) {E.printstacktra CE ();} catch (IOException e)}//finally}//public static void Main (string[] args)}//public class serverreceive


Client source code:
Import Java.io.file;import java.io.fileinputstream;import Java.io.filenotfoundexception;import java.io.IOException ; Import Java.io.outputstream;import java.io.printstream;import java.net.socket;/** * * File name: Clientsend.java * Implementation function: Send a file as a client to the server * * Specific implementation process: * 1, establish a connection with the server side, ip:127.0.0.1, port:4004 * 2, the name and size of the file through a custom file transfer protocol, send to the server * 3, loop read local files, the text  Package sent to the data output stream * 4, close the file, end the transfer * * "NOTE: This code only for the demo client and server transfer files use, * each packet before the file Protocol command * Specific protocol transfer and file out of the use phase can be placed on their own program" * * * Small rookie * Creation Time: 2014-08-19 * * */public class Clientsend {public static void main (string[] args) {/** communication handle to the server connection */socket s = null /** defines a file object, which is the file to be sent * if you use an absolute path, do not forget to use the difference between '/' and ' \ ' * Specific differences, please query the reader by themselves * */file sendfile = new File ("API. CHM ");/** definition file input stream to open, read the file to be sent */fileinputstream FIS = null;/** defines a byte array to be the packet's storage packet */byte[] buffer = new byte[4096 * 5 ];/** defines the output stream, outputs the packet using the outputstream of the socket */outputstream OS = null;/** checks to see if the file to be sent exists */if (!sendfile.exists ()) { SYSTEM.OUT.PRINTLN ("Client: The file to be sent does not exist"); return;} /** connection to the server */try {s = new Socket ("127.0.0.1",4004);} catch (IOException e) {System.out.println ("Not connected to Server");} /** initializes the FIS object with a file object * to make it possible to extract the size of the file * */try {fis = new FileInputStream (sendfile);} catch (FileNotFoundException E1) {E1.print StackTrace ();} /** first sends information about the file to the server, so that the server can receive the relevant preparations * specific preparations, please review the server code. * * Sent content includes: Send file protocol code (here is 111)/#文件名 (with suffix name)/#文件大小 * */try {printstream PS = new PrintStream (S.getoutputstream ());p s.println ( "111/#" + sendfile.getname () + "/#" + fis.available ());p S.flush (); catch (IOException e) {System.out.println ("Server connection Interrupted");} /** * Here sleep 2s, waiting for the server to prepare the relevant work * also to ensure the delay of the network * readers can choose to add this code * */try {thread.sleep;} catch (Interruptedexception E1) {E1 . Printstacktrace ();} /** before the end of the preparation work * The following is the key code for file transfer * */try {/** Gets the outputstream of the socket in order to write packets to it */os = S.getoutputstream ();/** size Used to record the size of each read file */int size = 0;/** uses while loop to read the file until the end of the file read */while ((size = fis.read (buffer))! =-1) {System.out.println (" The client sends the packet with a size of "+";/** writes the packet just read to the output stream */os.write (buffer, 0, size);/** refresh */os.flush ();}} catch (FileNotFoundException e) {SYSTEM.OUT.PRINTLN ("Client read file Error");} catch (IOException e) {System.out.println ("error in client output file");} finally{/** * Close Open File * If required, you can also close the socket connection * */try {if (FIS! = null) Fis.close (),} catch (IOException e) {System.out.prin TLN ("Client file shutdown error");} catch (IOException e)}//finally}//public static void Main (string[] args)}//public class Clientsend


 

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.