Basic knowledge
Client: refers to the browser or custom client.
Server: like Tomcat server or custom client.
TCP/IP
TCP: transport layer protocol.
IP: network layer protocol.
TCP/UDP
Difference between TCP and UDP
TCP use case: used for RPC interface calls, sending e-mail and other things that need reliable transmission.
UDP use case: used for video transmission.
Similarities:
- Both TCP and UDP are network layer communication protocols, but the communication protocols are different.
difference:
- TCP protocol should establish a connection through three handshakes before communication to ensure the reliability of communication. UDP does not need to establish a connection and can send packets, so the receiver may not receive it, so it is unreliable.
- TCP protocol needs to establish and release connections, so the transmission efficiency is low. UDP does not need to release resources, so it has low overhead and high speed.
- UDP can broadcast and send, while TCP is point-to-point communication.
- TCP can transmit a large amount of data after establishing a connection, while UDP will limit the transmission size of each packet to less than 64K.
TCP
Three handshakes
Three handshakes when the client establishes a connection request:
First handshake: the client sends syn message and sequence number x to the server;
Second handshake: the server receives the request from the client, sends ack=x+1 message, and sends sequence number y, syn message.
The third Handshake: the client receives the request from the server, sends the ack= y+1 message, and sends the sequence number z.
Why three handshakes instead of two or four or five?
Therefore, according to the three handshakes, both our client and server can know that their sending is normal and the other party's receiving is normal; For the second handshake, the server does not know that its sending is normal, but only that the client sends and receives normally and receives normally, but does not know that its sending is normal. And three handshakes just meet this condition. Since three handshakes are satisfied, four or five handshakes will be redundant. Although more handshakes can more ensure the normal communication, normally, three handshakes can ensure that 99% of the communication is reliable. The improvement of the reliability of repeated handshakes is not high and of little significance.
Four waves
The client server can close the connection by waving four times, but generally the client sends four waving requests to close the connection, because our server is generally 24-hour online service.
Take the disconnection initiated by the client as an example:
The client told the server that I was going to disconnect.
The corresponding client of the server said that I received your disconnect request.
The server disconnects and sends a request to tell the client that I have disconnected from you.
When the client receives the disconnection request, it disconnects and sends a request to confirm the disconnection to tell the service that I disconnected from you. At this time, the server cannot receive the client's request. If it receives it, it means that it has not really disconnected.
Example summary
public class TCPTest { /** * client */ @Test public void client() throws IOException { Socket socket = null; OutputStream os = null; try { InetAddress inetAddress = InetAddress.getByName("127.0.0.1"); //1 create a Socke connection object to indicate the ip and port number of the server to be connected socket = new Socket(inetAddress, 9000); //2 obtain the output stream for outputting data os = socket.getOutputStream(); //3 write data os.write("My name is client. Hello".getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { //4 close stream resources if (os != null) { os.close(); } if (socket != null) { socket.close(); } } } @Test public void server() throws IOException { InputStream is = null; ByteArrayOutputStream baos = null; ServerSocket serverSocket = null; Socket socket = null; try { //Create a server socket on the server side, indicate its own port number, and connect the client through the specified ip and the port number determination process serverSocket = new ServerSocket(9000); //accept() is used to receive connections from clients socket = serverSocket.accept(); //Get input stream is = socket.getInputStream(); //Read the data in the input stream. ByteArrayOutputStream maintains the dynamic array and saves the written data baos = new ByteArrayOutputStream(); byte[] buff = new byte[1024]; int len; while ((len = is.read(buff)) != -1) { baos.write(buff, 0, len); } System.out.println(baos.toString()); System.out.println("Received the client request!"); } catch (IOException e) { e.printStackTrace(); } finally { //close resource baos.close(); is.close(); socket.close(); serverSocket.close(); } } /** * My name is client. Hello * Received the client request! */ }
Example Summary - TCP send and receive files
public class TCPFileTest { /** * The client sends a file to the server */ @Test public void client() throws IOException { Socket socket = null; OutputStream os = null; FileInputStream fis = null; ByteArrayOutputStream baos = null; try { InetAddress inetAddress = InetAddress.getByName("127.0.0.1"); //1 create a Socke connection object to indicate the ip and port number of the server to be connected socket = new Socket(inetAddress, 9000); //2 obtain the output stream for outputting data os = socket.getOutputStream(); fis = new FileInputStream("It's a minister.jpg"); //3 write data byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { os.write(buffer, 0, len); } System.out.println("Sending pictures to the server succeeded!"); //Turn off the data output, or the server will block the reception all the time socket.shutdownOutput(); //Receive the response from the server InputStream is = socket.getInputStream(); baos = new ByteArrayOutputStream(); byte[] buff = new byte[1024]; int length; while ((length = is.read(buff)) != -1) { baos.write(buff, 0, length); } System.out.println(baos.toString()); } catch (IOException e) { e.printStackTrace(); } finally { //4 close stream resources if (os != null) { os.close(); } if (socket != null) { socket.close(); } } } /** * Sending pictures to the server succeeded! * Client, your file has been received */ /** * The server receives the file and saves it locally * * @throws IOException */ @Test public void server() throws IOException { InputStream is = null; FileOutputStream fos = null; ServerSocket serverSocket = null; Socket socket = null; OutputStream os = null; try { //Create a server socket on the server side, indicate its own port number, and connect the client through the specified ip and the port number determination process serverSocket = new ServerSocket(9000); //accept() is used to receive connections from clients socket = serverSocket.accept(); //Get input stream is = socket.getInputStream(); //Open output stream write file fos = new FileOutputStream("It's a minister-copy5.jpg"); byte[] buff = new byte[1024]; int len; while ((len = is.read(buff)) != -1) { fos.write(buff, 0, len); } System.out.println("Received the client request!"); //Write a reply to the client os = socket.getOutputStream(); os.write("Client, your file has been received".getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { //close resource fos.close(); is.close(); socket.close(); serverSocket.close(); os.close(); } } /** * Received the client request! */ }
UDP
Example summary
public class UDPTest { /** * Generating end */ @Test public void sender() throws IOException { //1 to create a socket, the sender does not need to specify the ip and port to occur, but directly specify the receiving address port in the packet to occur. DatagramSocket socket = new DatagramSocket(); byte[] data = "I'm the sender. This is a letter for you!".getBytes(); //Address to send the packet InetAddress address = InetAddress.getByName("127.0.0.1"); //2 create send package DatagramPacket packet = new DatagramPacket(data, 0, data.length, address, 9999); //3 send socket.send(packet); System.out.println("Sending data succeeded!"); //4 close flow socket.close(); } /** * receiving end */ @Test public void receiver() throws IOException { //1. To create a socket at the receiving end, you must specify the port number of the receiving end before receiving DatagramSocket socket = new DatagramSocket(9999); //2 create an array container for receiving data streams byte[] buffer = new byte[1024]; //2 create a receiving packet for receiving data packets DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length); //3 send socket.receive(packet); //4 print received data System.out.println(new String(packet.getData(),0,packet.getLength())); System.out.println("Data received successfully!"); //5 close flow socket.close(); } }
URL
Example summary
public class URLTest { /** * Use url to download network files * * @throws IOException */ @Test public void urlTest() throws IOException { //The URL is equivalent to a seed URL url = new URL("https://pics4.baidu.com/feed/d009b3de9c82d1586f9efd2871ac9ad1bd3e42bf.jpeg?token=dd219671927c0cb92aebbd8808110a70"); //Force different urlconnections, HttpURLConnection or HttpURLConnection according to different protocols HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); InputStream is = urlConnection.getInputStream(); //Write local BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("pic.jpeg")); byte[] buff = new byte[1024]; int len; while ((len = is.read(buff)) != -1) { bos.write(buff, 0, len); } System.out.println("Download succeeded!"); //Close flow is.close(); bos.close(); urlConnection.disconnect(); } }
reference resources
Getting started with Java video tutorial
618-630