preface

What is a Socket? It is the cornerstone of computer network communication based on TCP/IP protocol. We can think of it abstractly as IP+ port number. Its essence is a programming interface (API), the encapsulation of TCP/IP. Understanding sockets helps us better understand the Http protocol.

1 Network Model

Network architecture models mainly include OSI reference model and TCP/IP five-layer model.We usually use the TCP/IP five-tier network model.

As shown in the figure, common network protocols at the application layer include Http, Https, and FTP. There are only two transport layers, TCP and UDP.

The mainstreamHttp1.1Also based on TCP to achieve persistent connection.

2 Three handshakes and four waves

Knowing the network model, we can also look at the three-way handshake and the four-way wave.

Why three handshakes? It’s easy to understand that when a client requests a connection, it doesn’t know if the server is ready for the data transfer, so the server needs to send back a message saying it is. After receiving the message, the client knows that the server is ready. Based on reliability, the client needs to send a confirmation message again to inform the server that I received your message and ready to develop data transmission. After three handshakes, a stable connection is formed between the client and server.

Quadruple wave First the client sends a disconnection request (FIN) to the server. When the server receives the data, it cannot be disconnected immediately because there may be incomplete data transfer. So in terms of reliability, the server first sends a confirmation message (telling the client, I received your request to disconnect, please wait). After confirming that all data is transferred, the server sends a disconnection request. When the client receives the disconnection request, it actually disconnects, sends a confirmation message to the server, and the server disconnects.

3 the Http message

HTTP request packets

Example: GET request

GET /test HTTP/1.1 Host: 192.168.62.248:8080 upgrade-insecure -Requests: 1 User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml; Q = 0.9, image/avif, image/webp image/apng, * / *; Q = 0.8, application/signed - exchange; v=b3; Q =0.9 Accept-encoding: gzip, deflate Accept-language: zh-cn,zh; Q = 0.9 Connection: keep aliveCopy the code

The response message

HTTP / 1.1 200 the content-type: text/HTML. charset=UTF-8 Content-Length: 3 Date: Thu, 22 Apr 2021 06:15:51 GMT Keep-Alive: timeout=60 Proxy-Connection: keep-alive aaaCopy the code

“Aaa” is the response data returned by the server.

4 Socket Encapsulates Http request implementation

After understanding the basic network architecture model, three-way handshake, four-way wave, and HTTP packets, the blogger uses socket to encapsulate the request to actually prove the HTTP packet structure as shown in the figure above.

try {
    StringBuffer requestMessage = new StringBuffer(); // Request message
    requestMessage.append("GET/HTTP / 1.0 \ r \ n"); / / request
	// Omit the request header
    requestMessage.append("\r\n");
    // omit the text

    // The kernel completes the three-way handshake when establishing a connection through the socket
    Socket socket = new Socket();
    SocketAddress socketAddress = new InetSocketAddress("www.baidu.com".80); // ip + port
    socket.connect(socketAddress); // Establish a connection

    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    bufferedWriter.write(requestMessage.toString());
    bufferedWriter.flush();

    InputStream inputStream = socket.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    String line;
    while((line = bufferedReader.readLine()) ! =null) {
        System.out.print(line + "\n");
    }
    inputStream.close();
} catch (IOException e) {
    e.printStackTrace();
}
Copy the code

Program running result

summary

Socket is the intermediate software abstraction layer of communication between application layer and TCP/IP protocol family. It is a group of interfaces. In the design mode, Socket is actually a facade mode, it hides the complex TCP/IP protocol family behind the Socket interface, for the user, a simple set of interfaces is all, let the Socket to organize data to conform to the specified protocol. Through the above socket encapsulation HTTP request, presumably you have a deeper understanding of the HTTP protocol. Later, if you want to customize protocols for communication, HTTP is a great reference!