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
- [Client] input stream, read the file data from the hard disk to the program.
- [Client] output stream, write out the file data to the server.
- [server] input stream, read the file data to the server program.
- [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