The java implementation client sends files to the server

  • 2020-12-21 18:02:38
  • OfStack

The example of this paper shares the specific code of java client sending files to the server for your reference. The specific content is as follows

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; 
  
/** 
 * 
 *  The file name: ServerReceive.java 
 *  Functions: As a server to receive the file sent by the client  
 * 
 *  Specific implementation process:  
 * 1 , to set up the SocketServer , waiting for the client to connect  
 * 2 When there is a client connection, according to the agreement of both parties, at this time to read 1 Rows of data  
 *    It holds the file name and file size information to be sent by the client  
 * 3 Create a file locally according to the file name, and establish a good circulation letter  
 * 4 Receive the packet in a loop and write the packet to the file  
 * 5 When the length of the received data is equal to the length of the file sent in advance, it means that the file has been received, close the file  
 * 6 The document receiving work is finished  
 * 
 * 
 *  [Note: This code is only used to demonstrate client/server file transfer,  
 *    every 1 No file protocol command before the packet  
 *    Specific protocol transfer and file transfer stage can be placed according to their own procedures.]  
 * 
 * 
 *  Author: Rookie  
 *  Creation time: 2014-08-19 
 * 
 * */ 
 
public class ServerReceive { 
 
  public static void main(String[] args) { 
     
    /** A communication handle to establish a connection with the server */ 
    ServerSocket ss = null; 
    Socket s = null; 
     
    /** Defines file objects and file output stream objects that are created locally after receiving */ 
    File file = null; 
    FileOutputStream fos = null; 
     
    /** Define the input stream to use socket the inputStream Input the packet */ 
    InputStream is = null; 
     
    /** define byte Arrays are used as storage packets for packets */ 
    byte[] buffer = new byte[4096 * 5]; 
     
    /** The string used to receive a file send request */ 
    String comm = null; 
     
     
    /** To establish socekt Communicate and wait for the server to connect */ 
    try { 
      ss = new ServerSocket(4004); 
      s = ss.accept(); 
    } catch (IOException e) { 
      e.printStackTrace(); 
    } 
     
     
    /** read 1 Contract information sent by the line client */ 
    try { 
      InputStreamReader isr = new InputStreamReader(s.getInputStream()); 
      BufferedReader br = new BufferedReader(isr); 
      comm = br.readLine(); 
    } catch (IOException e) { 
      System.out.println(" The server is disconnected from the client "); 
    } 
     
    /** Start parsing the request command sent by the client */ 
    int index = comm.indexOf("/#"); 
     
    /** Determine if the protocol is a protocol for sending files */ 
    String xieyi = comm.substring(0, index); 
    if(!xieyi.equals("111")){ 
      System.out.println(" The protocol code received by the server is incorrect "); 
      return; 
    } 
     
    /** Resolves the name and size of the file */ 
    comm = comm.substring(index + 2); 
    index = comm.indexOf("/#"); 
    String filename = comm.substring(0, index).trim(); 
    String filesize = comm.substring(index + 2).trim(); 
     
     
    /** Creates an empty file for receiving files */ 
    file = new File(filename); 
    if(!file.exists()){ 
      try { 
        file.createNewFile(); 
      } catch (IOException e) { 
        System.out.println(" Server side file creation failed "); 
      } 
    }else{ 
      /** You can also ask for overrides here */ 
      System.out.println(" This path already exists in the same file, overwrite "); 
    } 
     
    /** [This is the preparation of the server written in the client code] */ 
     
     
    /** 
     *  The key code that the server receives the file */ 
    try { 
      /** Wrap the file into a file output stream object */ 
      fos = new FileOutputStream(file); 
      long file_size = Long.parseLong(filesize); 
      is = s.getInputStream(); 
      /**size Is the length of each packet received */ 
      int size = 0; 
      /**count Used to record the length of the received file */ 
      long count = 0; 
       
      /** use while Cyclic receive packet */ 
      while(count < file_size){ 
        /** Read from the input stream 1 A packet */ 
        size = is.read(buffer); 
         
        /** Write the packet you just read to a local file */ 
        fos.write(buffer, 0, size); 
        fos.flush(); 
         
        /** The length of the file will have been received +size*/ 
        count += size; 
        System.out.println(" The server side receives the packet with the size of " + size); 
      } 
       
    } catch (FileNotFoundException e) { 
      System.out.println(" The server failed to write the file "); 
    } catch (IOException e) { 
      System.out.println(" Server: Client disconnects "); 
    }finally{ 
      /** 
       *  Closes an open file  
       *  It can also be closed here if necessary socket The connection  
       * */ 
      try { 
        if(fos != null) 
          fos.close(); 
      } catch (IOException e) { 
        e.printStackTrace(); 
      }//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; 
 
 
/** 
 * 
 *  The file name: ClientSend.java 
 *  Functions: sent to the server as a client 1 A file  
 * 
 *  Specific implementation process:  
 * 1 , establish a connection with the server, IP : 127.0.0.1 .  port : 4004 
 * 2 Send the name and size of the file to the server via a custom file transfer protocol  
 * 3 , read the local file loop, package the file and send it to the data output stream  
 * 4 , close the file and end the transfer  
 * 
 *  [Note: This code is only used to demonstrate client/server file transfer,  
 *    every 1 No file protocol command before the packet  
 *    Specific protocol transfer and file transfer stage can be placed according to their own procedures.]  
 * 
 * 
 *  Author: Rookie  
 *  Creation time: 2014-08-19 
 * 
 * */ 
 
public class ClientSend { 
 
  public static void main(String[] args) { 
     
    /** A communication handle to establish a connection with the server */ 
    Socket s = null; 
     
    /** Defines the file object that is the file to be sent  
     *  If you use an absolute path, don't forget to use it '/' and '\' The difference between  
     *  Specific distinction, ask reader to inquire by oneself  
     * */ 
    File sendfile = new File("API.CHM"); 
    /** Defines a file input stream used to open and read files to be sent */ 
    FileInputStream fis = null; 
    /** define byte Arrays are used as storage packets for packets */ 
    byte[] buffer = new byte[4096 * 5]; 
     
    /** Define the output stream to use socket the outputStream Output the packet */ 
    OutputStream os = null; 
     
     
    /** Check if the file to be sent exists */ 
    if(!sendfile.exists()){ 
      System.out.println(" Client: The file to be sent does not exist "); 
      return; 
    } 
     
     
    /** Establish a connection with the server */ 
    try { 
      s = new Socket("127.0.0.1", 4004); 
    }catch (IOException e) { 
      System.out.println(" Not connected to server "); 
    } 
     
    /** Class with a file object fis object  
     *  So that the file size can be extracted  
     * */ 
    try { 
      fis = new FileInputStream(sendfile); 
    } catch (FileNotFoundException e1) { 
      e1.printStackTrace(); 
    } 
 
     
    /** First send the information about the file to the server, so that the server to receive the relevant preparation work  
     *  For detailed preparation, please check the server code.  
     * 
     *  The content sent includes: send file protocol code (here is 111 ) /# File name (with suffix) /# The file size  
     * */ 
    try { 
      PrintStream ps = new PrintStream(s.getOutputStream()); 
      ps.println("111/#" + sendfile.getName() + "/#" + fis.available()); 
      ps.flush(); 
    } catch (IOException e) { 
      System.out.println(" Server connection break "); 
    } 
     
     
    /** 
     *  You sleep here 2s , waiting for the server to get the relevant work ready  
     *  Also to ensure network latency  
     *  You can add this code of your choice  
     * */ 
    try { 
      Thread.sleep(2000); 
    } catch (InterruptedException e1) { 
      e1.printStackTrace(); 
    } 
     
     
     
    /** After all the preparatory work is done  
     *  Here is the key code for the file transfer  
     * */ 
    try { 
       
      /** To obtain socket the OutputStream To write packets to it */ 
      os = s.getOutputStream(); 
       
      /** size  Used to record the size of each file read */ 
      int size = 0; 
       
      /** use while Iterate through the file until the end of the file reading */ 
      while((size = fis.read(buffer)) != -1){ 
        System.out.println(" The client sends a packet with the size of " + size); 
        /** Writes the packet you just read to the output stream */ 
        os.write(buffer, 0, size); 
        /** The refresh 1 Under the */ 
        os.flush(); 
      } 
    } catch (FileNotFoundException e) { 
      System.out.println(" There was an error reading the file from the client "); 
    } catch (IOException e) { 
      System.out.println(" There is an error in the client output file "); 
    }finally{ 
       
      /** 
       *  Closes an open file  
       *  It can also be closed here if necessary socket The connection  
       * */ 
      try { 
        if(fis != null) 
          fis.close(); 
      } catch (IOException e) { 
        System.out.println(" Error closing client file "); 
      }//catch (IOException e) 
    }//finally 
     
  }//public static void main(String[] args) 
}//public class ClientSend 

Related articles: