>** Experience :** > I am a self-taught java About to graduate from college > The purpose of summarizing notes is to make yourself better understand and deepen my impression . It may not be so beautiful , I wish I could understand it > * All the files and source code are open source in **GitHub**: [**https://github.com/kun213/JavaNotes**](https://github.com/kun213/JavaNotes/) Yes *. I hope we can refuel together , Learn together , Communicate together ## day14 【 Network programming 】 @[toc]( Today's learning content -2020.10.16) ## One 、 Introduction to network programming ### 1.1 You can tell the structure of the software **C/S Structure ** : Its full name is Client/Server Structure , It refers to the client and server structure . Common programs are QQ、 Xunlei and other software . **B/S Structure ** : Its full name is Browser/Server Structure , Browser and server architecture . Common browsers are Google 、 Foxes, etc . ### 1.2 You can say UDP and TCP Protocol features - **TCP**: Transmission control protocol (Transmission Control Protocol).TCP The agreement is ** Connection oriented ** Communication protocol for , Before the data is transmitted , Establish a logical connection between the sender and the receiver , And then transmit the data , It provides reliable error free data transmission between two computers . - Three handshakes :TCP In the agreement , In the preparation stage of transmitting data , Three interactions between client and server , To ensure the reliability of the connection . - The first handshake , The client sends a connection request to the server , Wait for the server to confirm . - The second handshake , The server sends back a response to the client , Notify the client that a connection request has been received . - The third handshake , The client sends the confirmation information to the server again , Confirm the connection . The whole interaction process is shown in the figure below  Complete three handshakes , After the connection is established , The client and server can start data transfer . Because of this connection oriented feature ,TCP The protocol can guarantee the security of the transmitted data , So it's widely used , For example, downloading files 、 Browsing the web, etc . - **UDP**: User datagram protocol (User Datagram Protocol).UDP The agreement is a ** Facing no connection ** Agreement of . When transmitting data , There is no need to establish a connection , No matter whether the other side service is started or not , Directly put the information 、 Data sources and destinations are encapsulated in data packets , Direct transmission . The size of each packet is limited to 64k Within . It's an unreliable protocol , Because there's no connection , So the transmission speed is fast , But it's easy to lose data . In daily use , For example, video conferencing 、QQ Chat, etc . The maximum amount of data transmitted each time is 64kb. ## Two 、TCP Communication protocol ### 2.1 You can say TCP Two common class names under the protocol ** stay Java in , Two classes are provided to implement TCP Communication program :** - Client :`java.net.Socket` Class representation . establish `Socket` thing , Send a connection request to the server , The server responds to the request , The two establish a connection and begin to communicate . - Server-side :`java.net.ServerSocket` Class representation . establish `ServerSocket` thing , It is equivalent to opening a service , And wait for the client to connect . ### 2.2 How to write TCP Protocol string data transfer program Realize TCP Communication client program : ```java /** * Realize TCP Communication client program * * java.net.Socket Implement the socket object of the client , Connecting objects * * demand : Client program and server program realize data exchange * * Implementation steps : * 1: establish Socket thing ( Actively connect to the server ) * Socket(String host, int port) * * 2: OutputStream getOutputStream() * Returns the byte output stream in the socket * Method write Write data , Write to the server * * 3: InputStream getInputStream() * Returns the byte input stream in the socket * Method read Read data , It reads the data sent back by the server * * 4: Releasing resources */ public class TCPClient { public static void main(String[] args)throws IOException { // establish Socket thing ( Actively connect to the server ) Socket socket = new Socket("127.0.0.1",9000); //OutputStream getOutputStream() OutputStream out = socket.getOutputStream(); // Byte stream method to write data out.write(" Hello server ".getBytes());// It's not in the file , Written to the server InputStream in = socket.getInputStream();// Get byte input stream byte[] bytes = new byte[1024]; int len = in.read(bytes);// Client input stream , Read the data sent back from the server System.out.println(new String(bytes,0,len)); // Releasing resources //out.close(); socket.close(); } } ``` Realize TCP Communication server program : ```java /** * Realize TCP Communication server program * 192.168.27.95 * java.net.ServerSocket Realize TCP Server socket object in protocol * * Realize TCP Server program steps : * 1: establish ServerSocket thing * ServerSocket(int port) Port number * * 2: Waiting for the client to connect , If there is no client connection , Always wait for * ServerSocket Class method accept() agree! * Method accept() The return value is Socket thing ( Client connection object , Contains the client IP) * * 3: Socket Get in place tuple output stream from object * OutputStream getOutputStream() * Method write Writing materials , Write to client * * 4: Socket Object to get in place tuple input stream * InputStream getInputStream() * Method read Read data , Read the data from the client * * 5: Releasing resources */ public class TCPServer { public static void main(String[] args)throws IOException { // establish ServerSocket thing ServerSocket server = new ServerSocket(9000); //ServerSocket Class method accept() agree! Socket socket = server.accept(); //System.out.println(socket); // Use the client connection to get the object , Input stream InputStream in = socket.getInputStream(); //in Input stream method read() Read the data sent by the client byte[] bytes = new byte[1024]; //len The number of bytes read is returned int len = in.read(bytes); System.out.println(new String(bytes,0,len)); //Socket Client object , Get byte output stream OutputStream out = socket.getOutputStream(); out.write(" received !".getBytes());// Server output stream , Write back to the client // Releasing resources socket.close(); server.close(); } } ``` ### 2.3 understand TCP File upload cases under the agreement  Realize image upload client : ```java /** * Realize TCP Image upload client * Implementation steps : * 1: establish Socket thing , Connect to the server * 2: FileInputStream Read mm.jpg Array of bytes * 3: Socket Object gets the byte output stream * Array of bytes , To the output stream , Write to the server * 4: Socket Object gets the byte input stream * All the pictures have been transferred * Input stream , Read the prompt information from the server " Upload successful " * * Client method Socket: shutdownOutput() Terminate the output stream of the connected object , * At the same time, keep up with TCP Termination sequence * 5: Releasing resources */ public class TCPClient { public static void main(String[] args) throws IOException{ //1: establish Socket thing , Connect to the server Socket socket = new Socket("127.0.0.1",9000); //2: Its own byte input stream , Read the picture mm.jpg FileInputStream fis = new FileInputStream("e:/msh.jpg"); //3: Socket Object gets the byte output stream OutputStream out = socket.getOutputStream();// Any information , Write to the server byte[] bytes = new byte[1024]; int len = 0; //fis Read the end of the file ,JVM return read() -1 while ((len = fis.read(bytes))!=-1){ out.write(bytes,0,len); } // Tell the server , No more information , Don't read , The server sends TCP The terminator of socket.shutdownOutput(); //4:Socket Object gets the byte input stream InputStream in = socket.getInputStream();// Input stream , Read the data from the server len = in.read(bytes); System.out.println(" Server prompt ::"+new String(bytes,0,len)); socket.close(); } } ``` Realize image upload server : ```java /** * Realize image upload server * Implementation steps : * 1: Create objects ServerSocket Binding port * 2: Socket accept() Method to wait for the client to connect * 3: Socket thing , Get byte input stream , Read the bytes of the image sent by the client * 4: Create a byte output stream , Read the picture , Write e:/upload * 5: Socket thing , Get byte output stream ," Upload successful " Write back to the client * * bug: * 1: Demonstrated 2 Time , Why is there only one folder in the file , Cover with the same name * a: 1.jpg * b: 1.jpg * * 2: The client failed to receive the upload from the server // Tell the server , No more information , Don't read , The server sends TCP The terminator of */ public class TCPServer { public static void main(String[] args) throws IOException{ //1: Create objects ServerSocket Binding port ServerSocket server = new ServerSocket(9000); // 2: Socket accept() Method to wait for the client to connect Socket socket = server.accept(); //3: Socket thing , Get byte input stream , Read the bytes of the image sent by the client InputStream in = socket.getInputStream(); //4: Create a byte output stream , Read the picture , Write e:/upload // Uploaded files , Rename , Get the current date Convert to string String filename = new SimpleDateFormat("yyyyMMddHHmmssssss").format(Calendar.getInstance().getTime())+".jpg"; FileOutputStream fos = new FileOutputStream("e:/upload/"+filename); byte[] bytes = new byte[1024]; int len = 0; //read() Reading is a picture written by the client !! while ( (len = in.read(bytes))!=-1){ fos.write(bytes,0,len); } //5: Socket thing , Get byte output stream ," Upload successful " Write back to the client OutputStream out= socket.getOutputStream(); out.write(" Upload successful !".getBytes()); socket.close(); server.close(); } } ``` ------ *** This is my public number , I hope you can pay attention to , Let's be our best selves together . I will also share my self-study video on it , For everyone to learn together .*** 