A brief analysis of Java file transfer case based on Socket

  • 2020-05-05 11:13:42
  • OfStack

This paper introduces the file transfer case of Java based on Socket as an example and shares it with you for your reference. The specific content is as follows:

1. Java code


package com.wf.demo.socket.socketfile; 
 
import java.net.*; 
import java.io.*; 
 
/** 
 * 2.socket the Util Auxiliary class  
 * 
 * @author willson 
 * 
 */ 
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 The connection  
   * 
   * @throws Exception 
   *       exception 
   */ 
  public void CreateConnection() throws Exception { 
 
    try { 
      socket = new Socket(ip, port); 
    } catch (Exception e) { 
      e.printStackTrace(); 
      if (socket != null) 
        socket.close(); 
      throw e; 
    } finally { 
    } 
  } 
 
  //  Send a message  
  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; 
    } finally { 
    } 
  } 
 
  //  Receive a message  
  public DataInputStream getMessageStream() throws Exception { 
    try { 
      getMessageStream = new DataInputStream(new BufferedInputStream( 
          socket.getInputStream())); 
      return getMessageStream; 
    } catch (Exception e) { 
      e.printStackTrace(); 
      if (getMessageStream != null) 
        getMessageStream.close(); 
      throw e; 
    } finally { 
    } 
  } 
 
  //  Close the connection  
  public void shutDownConnection() { 
    try { 
      if (out != null) 
        out.close(); 
      if (getMessageStream != null) 
        getMessageStream.close(); 
      if (socket != null) 
        socket.close(); 
    } catch (Exception e) { 
    } 
  } 
} 

2. Java code


package com.wf.demo.socket.socketfile; 
 
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; 
 
/** 
 * 1. The server side  
 * 
 * @author willson 
 * 
 */ 
public class ServerTest { 
   
  int port = 8821; 
 
  void start() { 
     
    Socket socket = null; 
     
    try { 
       
      ServerSocket serverSocket = new ServerSocket(port); 
       
      while (true) { 
        //  Select the file for transfer  
        String filePath = "E:\\lib.zip"; 
         
        File fi = new File(filePath); 
 
        System.out.println("File Name : " + fi.getName() + ";\tFile Size() : " + (int) fi.length() + "bytes"); 
 
        // public Socket accept() throws 
        // IOException Listens for and accepts a connection to this socket. This method blocks until the connection is made.  
 
         
        System.out.println(" Waiting for client connection, connection port: " + port); 
        socket = serverSocket.accept(); 
         
        System.out.println(" To establish socket link "); 
         
        DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream())); 
         
        dis.readByte(); 
 
        DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath))); 
         
        DataOutputStream ps = new DataOutputStream(socket.getOutputStream()); 
         
        //  Pass the file name and length to the client. Here to really apply to all platforms, such as Chinese name processing, but also need to process, specific can see Think In Java 
        // 4th There's code out there.  
        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(); 
        //  Pay attention to shut down socket Link, or the client will wait server The data comes in,  
        //  until socket Timeout, resulting in incomplete data.  
        fis.close(); 
        socket.close(); 
         
        System.out.println(" File transfer completed \n"); 
      } 
 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
  } 
 
  public static void main(String arg[]) { 
    new ServerTest().start(); 
  } 
} 
 
 


3. Client


package com.wf.demo.socket.socketfile; 
 
import java.io.BufferedOutputStream; 
import java.io.DataInputStream; 
import java.io.DataOutputStream; 
import java.io.FileOutputStream; 
 
/** 
 * 3. The client  
 * 
 * @author willson 
 * 
 */ 
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("F:\\"); 
      } 
    } catch (Exception ex) { 
      ex.printStackTrace(); 
    } 
  } 
 
  private boolean createConnection() { 
     
    cs = new ClientSocket(ip, port); 
    try { 
      cs.CreateConnection(); 
      System.out.print(" Server connection successful !" + "\n"); 
      return true; 
    } catch (Exception e) { 
      System.out.print(" Connection to server failed !" + "\n"); 
      return false; 
    } 
 
  } 
 
  private void sendMessage() { 
     
    if (cs == null) 
      return; 
    try { 
      cs.sendMessage(sendMessage); 
    } catch (Exception e) { 
      System.out.print(" Failed to send message !" + "\n"); 
    } 
  } 
 
  private void getMessage(String savePath) { 
     
    if (cs == null) 
      return; 
    DataInputStream inputStream = null; 
    try { 
      inputStream = cs.getMessageStream(); 
    } catch (Exception e) { 
      System.out.print(" Received message cache error \n"); 
      return; 
    } 
 
    try { 
       
      //  Save the path locally and the file name is automatically inherited from the server.  
      int bufferSize = 8192; 
      byte[] buf = new byte[bufferSize]; 
      int passedlen = 0; 
      long len = 0; 
 
      savePath += inputStream.readUTF(); 
      DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(savePath)))); 
      len = inputStream.readLong(); 
 
      System.out.println("File Size() : " + len + "bytes"); 
      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 for graphical interface prograssBar So what you do, if you're typing a file here, you might print out some of the same percentages over and over again  
        System.out.println(" File received " + (passedlen * 100 / len) + "%\n"); 
        fileOut.write(buf, 0, read); 
      } 
      System.out.println(" Receive completed, file saved as " + savePath + "\n"); 
 
      fileOut.close(); 
    } catch (Exception e) { 
      System.out.println(" Receiving message error " + "\n"); 
      return; 
    } 
  } 
 
  public static void main(String arg[]) { 
    new ClientTest(); 
  } 
} 

I hope this article is helpful for you to learn java programming.


Related articles: