Java -- using TCP to upload files

Java -- using TCP to upload files

Blog description

The information involved in this article comes from Internet collation and personal summary, which means personal learning and experience summary. If there is any infringement, please contact me to delete, thank you!

graphic

step

  1. [Client] input stream, read the file data from the hard disk to the program.
  2. [Client] output stream, write out the file data to the server.
  3. [server] input stream, read the file data to the server program.
  4. [server] output stream, write out file data to server hard disk

code implementation

The server
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author ServerTCP
 * @date 2020/4/25 10:51 morning
 */
public class ServerTCP {
    public static void main(String[] args) throws IOException {
        System.out.println("Service started, waiting for connection");
        //Create ServerSocket object, bind port, start waiting for connection
        ServerSocket ss = new ServerSocket(8888);
        //accept method, return socket object
        Socket server = ss.accept();
        //Get input object, read file
        BufferedInputStream bis = new BufferedInputStream(server.getInputStream());
        //Save to local
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.txt"));

        //Create byte array
        byte[] b = new byte[1024 * 8];
        //Read character array
        int len;
        while ((len = bis.read(b)) != -1) {
            bos.write(b, 0, len);
        }

        //close resource
        bos.close();
        bis.close();
        server.close();
        System.out.println("Upload succeeded");
    }
}

client
import java.io.*;
import java.net.Socket;

/**
 * @author ClientTCP
 * @date 2020/4/25 10:58 morning
 */
public class ClientTCP {
    public static void main(String[] args) throws IOException {
        //Create input stream
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("in.txt"));
        //Create Socket
        Socket client = new Socket("127.0.0.1", 8888);
        //Output stream
        BufferedOutputStream bos = new BufferedOutputStream(client.getOutputStream());
        //Write data
        byte[] b = new byte[1024 * 8];
        int len;
        while ((len = bis.read(b)) != -1) {
            bos.write(b, 0, len);
            bos.flush();
        }
        System.out.println("File uploaded");

        //close resource
        bos.close();
        client.close();
        bis.close();
        System.out.println("File upload completed");
    }
}

Result

Thank

Black horse programmer

And the industrious self

Keywords: Programming socket Java

Added by varzosu on Sat, 25 Apr 2020 17:47:49 +0300