Requirement Description: make a "file upload case"
Requirement: upload a picture in the project to the server through the client
Operation steps:
1. Create the server and wait for the client to connect
2. Create a client Socket and connect to the server
3. Get the output stream in the Socket stream. Function: used to write data to the server
4. Create byte input stream, function: to read bytes of data source (picture)
5. Write the picture data to the output stream of Socket (transfer the data to the server)
6. After the client sends the data, the Socket output stream is written and the server is informed
7. Get the input stream of Socket
8. Create byte output stream of destination
9. Write the data in the Socket input stream to the byte output stream of the destination
10. Get the output stream of the Socket. Function: write feedback information to the client
11. Write feedback information to the client
12. Get the input stream function of Socket: read the feedback information
13. Read feedback
Code:
Create server first:
public class TCPServer3 { public static void main(String[] args) throws IOException { //1 create server object ServerSocket server = new ServerSocket(9898); //2 wait for client connection if there is a client connection to get to the client object Socket s = server.accept(); //3 currently reading data in the server InputStream in = s.getInputStream(); //4 currently write data to stream in server FileOutputStream fos = new FileOutputStream("BBQ\\123.png"); byte[] bytes = new byte[1024]; int len = 0; while ((len = in.read(bytes)) != -1) { fos.write(bytes, 0, len); } //5. After writing the data, it indicates that the upload is successful s.getOutputStream().write("Upload success".getBytes()); //6 release resources fos.close(); s.close(); server.close(); } }
Create client after server creation:
public class TCPClient3 { public static void main(String[] args) throws IOException { //1 create server object Socket s = new Socket("127.0.0.1", 9898); //2 specify path FileInputStream fis = new FileInputStream("D:\\123.png"); //3 read server data OutputStream out = s.getOutputStream(); byte[] bytes = new byte[1024]; int len = 0; while ((len = fis.read(bytes)) != -1) { out.write(bytes, 0, len); } //4. Inform that the writing is completed s.shutdownOutput(); //5 write to server InputStream in = s.getInputStream(); len = in.read(bytes); System.out.println("The server:" + new String(bytes, 0, len)); //6 release resources fis.close(); s.close(); } }