A brief analysis of Java socket-based file transfer case _java

Source: Internet
Author: User
Tags flush getmessage

This article introduces Java based on socket file transfer case, share to everyone for your reference, the specific contents are as follows

1, Java code

Package com.wf.demo.socket.socketfile; 
Import java.net.*; 
 
Import java.io.*; 
 
  /** * 2.socket 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 connection * * @throws Exception * Exception/public void createconnection () t 
    Hrows Exception {try {socket = new socket (IP, port); 
      catch (Exception e) {e.printstacktrace (); 
      if (socket!= null) socket.close (); 
    Throw e; ' Finally {}}//Send message public void SendMessage (String SendMessage) throws Exception {try {o 
      UT = 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 {}}//Accept Message Public DataInputStream Getmessagestream () throws Exception {try {get 
      Messagestream = new DataInputStream (New Bufferedinputstream (Socket.getinputstream ())); 
    return getmessagestream; 
      catch (Exception e) {e.printstacktrace (); 
      if (getmessagestream!= null) getmessagestream.close (); 
    Throw e; ' Finally {}}//close connection public void Shutdownconnection () {try {if (out!= null) out 
   . Close ();   if (getmessagestream!= null) getmessagestream.close (); 
    if (socket!= null) socket.close ();  The 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 Server-side * * @author Willson * */public class Servertest {int port = 8821; 
     
    void Start () {socket socket = NULL; 
       
      try {serversocket serversocket = new ServerSocket (port); 
         
        while (true) {//Select file to be transmitted String FilePath = "E:\\lib.zip"; 
 
        File fi = new file (FilePath); 
 
        System.out.println ("File Name:" + fi.getname () + "; \tfile Size ():" + (int) fi.length () + "bytes"); The public Socket accept () throws//IOException listens for and accepts connections to this socket. 
 
         
        This method blocks until the connection is made. 
        System.out.println ("Wait for client to connect, connect port:" + port); 
         
        Socket = Serversocket.accept (); SYSTEM.OUT.PRINTLN ("Establish the socket chainNext "); 
         
        DataInputStream dis = new DataInputStream (New Bufferedinputstream (Socket.getinputstream ())); 
 
        Dis.readbyte (); 
         
        DataInputStream fis = new DataInputStream (new Bufferedinputstream (new FileInputStream)); 
         
        DataOutputStream PS = new DataOutputStream (Socket.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 code in the Find in Java/4th. 
        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 server data to come over,//until SOcket timeout, resulting in incomplete data. 
        Fis.close (); 
         
        Socket.close (); 
      System.out.println ("File transfer complete \ 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. 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 ("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 (String savepath) {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. 
      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 ("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 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" + (Passedlen * 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 (); 
 } 
}

Hopefully this article will help you learn about Java programming.

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.