Socket learning network basic preparation


Introduction to this section:

In order to take care of beginners who have never learned Java Socket, or to understand the concepts related to network protocols involved in Android development, After all, during the interview, the interviewer asked me how many layers the network protocol has? So which layer is the IP protocol at? What the hell is Socket? What kinds? Which layer are the TCP and UDP protocols at? What's the difference... Well, this... So it's still useful to learn the conceptual theory of this section. necessary! So without further ado, let’s start this section~


1. A brief analysis of the OSI seven-layer network model

Of course, we are not professional in network engineering , as long as you know which layers there are and what they are used for!

OSI seven-layer network model (from bottom to top)

  • Physical layer (Physical): Provides transmission media and interconnection equipment for data communication between devices, providing reliable data transmission environment. It can be understood as the physical media part of network transmission, such as network card, network cable, hub, repeater, modem, etc.! At this layer, the data has not been organized and is only processed as a raw bit stream or electrical voltage. The unit of this layer is:bitbit
  • Data link layer (Datalink): It can be understood as a data channel. Its main function is how to operate on unreliable physical lines. Reliable transmission of data, layer modification functions include: physical address addressing, data framing, flow control, data error detection and retransmission, etc.! In addition, this data link refers to : The physical layer should provide transmission media and connections for data communication between terminal devices. media is Long-term, the connection has a lifetime. During the connection lifetime, the sending and receiving ends can conduct data communication one or more times. Every communication must go through two processes: establishing communication contacts and tearing down communication contacts! This established data sending and receiving relationship~ The devices at this layer include: Network card, network bridge, network switch, and the unit of this layer is: Frame
  • Network layer (Network): The main function is to translate the network address into the corresponding physical address and decide how to send the data from The sender routes to the receiver, so-called routing and path finding: one terminal may need to communicate with multiple terminals, which results in The problem of linking the data of any two terminal devices! To put it simply: establish a network connection and provide services to the upper layer! The devices at this layer include: routing! The unit of this layer is: packet, and the IP protocol is in this layer!
  • Transport layer (Transport): Provides communication services to the upper application layer, facing the highest layer of the communication part, and also The lowest level of user functionality. Receives session layer data, splits the data if necessary, and hands this data to the network layer, and ensure that these data segments effectively reach the opposite end! So the unit of this layer is: Data segment; and there are two very important ones in this layer The protocols are: TCP Transmission Control Protocol and UDP User Datagram Protocol, which are also the core part of this chapter!
  • Session layer (Session): Responsible for establishing, maintaining and terminating communication between two nodes in the network. Establish communication links, Keep the communication link open during the session, synchronize the dialogue between the two nodes, decide whether the communication is interrupted and when the communication is interrupted Decide where to resend from, i.e. the establishment and management of sessions between users on different machines!
  • Presentation layer(Presentation): Interpret commands and data from the application layer, and assign corresponding syntax to various syntaxes. meaning and transmitted to the session layer in a certain format.Its main function is to "handle user information representation issues, such as encoding, Data format conversion, encryption and decryption, compression and decompression", etc.
  • Application layer (Application): The highest layer of the OSI reference model, which provides network services for user applications. Based on the work of other 6 layers, it is responsible for completing the connection between applications and network operating systems in the network, establishing and ending connections between users, and completing various network services and applications required by network users. Various agreements for supervision, management and service. In addition, this layer is also responsible for coordinating the work between various applications. The services and protocols provided by the application layer for users include: file services, directory services, file transfer services (FTP), remote login services (Telnet), email services (E-mail), printing services, security services, network management services, Database services, etc.

Okay, above we have briefly described the OSI seven-layer network model. Here is a summary:

OSI is an ideal model. General network systems only There are several layers involved. In the seven-layer model, each layer provides a special Network functions, viewed from the perspective of network functions:

  • The following four layers (physical layer, data link layer, network layer and transport layer) mainly provide data transmission and exchange functions. That is, the communication between nodes is mainly focused on the communication between nodes
  • The fourth layer serves as a bridge between the upper and lower parts and is the most critical part of the entire network architecture;
  • The upper three layers (session layer , presentation layer and application layer) mainly provide information and data processing functions between users and applications.

In short, the lower 4 layers mainly complete the functions of the communication subnet, and the upper 3 layers mainly complete the functions of the resource subnet.

——The above content is referenced from: OSI seven-layer model detailed explanation


2.TCP/IP four-layer model

1.jpg

TCP/IP is synonymous with a group of protocols. It also includes many protocols that form the TCP/IP protocol cluster. The TCP/IP protocol cluster is divided into four layers. IP is located at the second layer of the protocol cluster (corresponding to the third layer of OSI), and TCP is located at the third layer of the protocol cluster. (Corresponding to the fourth layer of OSI). The TCP/IP communication protocol adopts a 4-layer hierarchical structure. Each layer calls the next layer to provide network to fulfill your needs. These 4 layers are:

  • Application layer: The layer for communication between applications, such as Simple Email Transfer (SMTP), File Transfer Protocol (FTP), Network Remote Access Protocol (Telnet), etc.
  • Transport layer: In this layer, it provides data transmission services between nodes, such as Transmission Control Protocol (TCP), User Datagram Protocol (UDP), etc., TCP and UDP add transmission data to the data packet and transmit it to the next layer, This layer is responsible for transmitting data and ensuring that the data has been delivered and received.
  • Network interconnection layer: Responsible for providing basic data packet transmission functions so that each data packet can reach the destination. host (but does not check whether it was received correctly), such as Internet Protocol (IP).
  • Host to network layer: Management of actual network media, defining how to use the actual network (such as Ethernet, Serial Line, etc.) to transmit data.

3.Explanation of the difference between TCP/UDP

Okay, the first two points are just for everyone to popularize the OSI seven-layer model and TCP/UDP The concept of IP four-layer model, what I want to talk about next is Here are some conceptual terms related to our Socket development!

1) IP address

2.png

2) Port

1. is used to distinguish between different Application

2. The port number range is 0-65535, of which 0-1023 are not system reserved ports. Our program should try not to use these ports!

3. The IP address and port number form our Socket. The Socket is the end point of the two-way communication link between network running programs. It is the basis of TCP and UDP!

4. Ports used by common protocols: HTTP: 80, FTP: 21, TELNET: 23

3.png

3 ) Comparison of TCP protocol and UDP protocol:

Detailed explanation of TCP protocol process:

First of all, TCP/IP is a protocol cluster, which includes many protocols. UDP is just one of them. The reason why it is named TCP/IP protocol is Because TCP and IP protocols are two very important protocols, they are named after them.

Let’s explain the difference between TCP protocol and UDP protocol:

TCP (Transmission Control Protocol, Transmission Control Protocol) is a connection-oriented protocol, that is, when sending and receiving data money , both need to establish a reliable link with the other party. This is also TCP's three-way handshake and TCP's four-way wave that are often asked in interviews! Three handshakes: When establishing a TCP connection, the client and server need to send a total of 3 packets to confirm the establishment of the connection. In Socket programming, this process is triggered by the client executing connect. The specific flow chart is as follows:

4.png

  • First handshake: Client sets the flag SYN to 1, randomly generates a value seq=J, and sends the data packet to the Server. The Client enters the SYN_SENT state and waits for confirmation from the Server.
  • Second handshake: After the Server receives the data packet, it knows that the Client requests to establish a connection by the flag bit SYN=1, and the Server sets the flag bit Both SYN and ACK are set to 1, ack=J+1, a value seq=K is randomly generated, and the data packet is sent to the Client to confirm the connection request. , the Server enters the SYN_RCVD state.
  • The third handshake: After the Client receives the confirmation, it checks whether the ack is J+1 and whether the ACK is 1. If it is correct, the flag is set to ACK Set to 1, ack=K+1, and send the data packet to the server. The server checks whether the ack is K+1 and whether the ACK is 1. If it is correct, The connection is established successfully, the Client and Server enter the ESTABLISHED state, complete the three-way handshake, and then the Client and Server can Data transfer begins.

Waving four times: Terminating a TCP connection means that when a TCP connection is disconnected, the client and server need to send a total of 4 packets to confirm the disconnection. In Socket programming, this process is triggered by either the client or the server executing close. The specific flow chart is as follows:

5.png

  • First time Waving : Client sends a FIN to close the data transfer from Client to Server, and Client enters FIN_WAIT_1 state
  • Second wave: After receiving the FIN, the Server sends an ACK to the Client, and the confirmation sequence number is the received sequence number + 1 (same as SYN, One FIN occupies one sequence number), and the Server enters the CLOSE_WAIT state.
  • The third wave: Server sends a FIN to close the data transmission from Server to Client, and Server enters LAST_ACK state.
  • The fourth wave: After the Client receives the FIN, the Client enters the TIME_WAIT state, and then sends an ACK to the Server. The confirmation sequence number is the received sequence number + 1, and the Server enters the CLOSED state, complete. Four waves. In addition, it may also be the case where a colleague initiates active closure:

6.png

#There may also be a common question: why is it a three-way handshake to establish a connection, but not a three-way handshake to close the connection? Is it waving four times? Answer: Because the server is in the LISTEN state and after receiving the SYN message for establishing a connection request, it puts ACK and SYN in one message. Sent to client. When closing the connection, when receiving the other party's FIN message, it only means that the other party no longer sends data but still If you can receive data, your side may not have sent all the data to the other party, so you can close it immediately, or you can send some After sending the data to the other party, send a FIN message to the other party to express agreement to close the connection now. Therefore, one's own ACK and FIN will generally send separately.


UDP protocol detailed explanation

UDP(User Datagram Protocol) User Datagram Protocol, a non-connection protocol, the source and terminal do not communicate before transmitting data. The connection is established and when it wants to be transmitted it simply grabs the data from the application and throws it over the network as quickly as possible. On the sending end, the speed at which UDP transmits data is only limited by the speed at which the application generates the data, the computer's capabilities, and the transmission bandwidth. Limitation; on the receiving end, UDP puts each message segment in the queue, and the application reads one message segment from the queue at a time. Compared with TCP, there is no need to establish a link, the structure is simple, the correctness cannot be guaranteed, and packet loss is easy

——The above content is partially excerpted from:

TCP/IP three-way handshake and Wave four times

The difference between TCP and UDP (transfer)


4. Several key classes provided for the network in Java:

For different network communication levels, Java provides us with four major categories of network functions:

  • InetAddress: Used to identify hardware resources on the network
  • URL: Uniform resource locator, you can directly read or write data on the network through the URL
  • Socket and ServerSocket: Socket-related classes that use TCP protocol to implement network communication
  • Datagram: Use UDP protocol to save data in datagrams and communicate through the network

In this section we only introduce the first two classes, Socket and Datagram, and then explain them in the chapters of TCP and UDP!

~Usage example of InetAddress:

Sample code:

public class InetAddressTest {
	public static void main(String[] args) throws Exception{
		//获取本机InetAddress的实例:
		InetAddress address = InetAddress.getLocalHost();
		System.out.println("本机名:" + address.getHostName());
		System.out.println("IP地址:" + address.getHostAddress());
		byte[] bytes = address.getAddress();
		System.out.println("字节数组形式的IP地址:" + Arrays.toString(bytes));
		System.out.println("直接输出InetAddress对象:" + address);
	}
}

Running result graph:

7.png

~URL: This goes without saying. If you forget, you can read the explanation of the Http protocol in the previous meeting~


Summary of this section:

This section is full of concepts. It may seem overwhelming, but it doesn’t matter if you don’t understand it. You know that each layer of the seven-layer model is called What, what is it probably used for? There are TCP three-way handshakes and four waves, and that’s it! Of course, this is just for Coping with interviews~ How can we struggle with this in actual development... Just Socket, right~ Well, we will start learning in the next section Socket communication in Android~Thank you~