1. Network transmission mode -TCP

This is the 12th day of my participation in the More text Challenge. For details, see more text Challenge

1.1 the TCP concept

Transmission Control Protocol (TCP) is a connection-oriented, reliable, and byte stream-based transport layer communication Protocol.

TCP communication requires three steps: creating a connection, transferring data, and terminating the connection.

In the TCP communication model, before the communication starts, the relevant link must be established before the data can be sent, similar to the “call” in life.

1.2 characteristics of TCP

1. Connection oriented

The communication parties must establish a connection before data can be transmitted. Both parties must allocate the necessary system kernel resources to the connection to manage the connection status and transmission.

Data transmission between two parties can be carried out through this one connection.

After the data exchange is complete, disconnect the connection to release system resources.

This connection is one-to-one, so TCP is not suitable for broadcast applications. For broadcast-based applications, use UDP.

2. Reliable transmission

  1. TCP uses the send reply mechanism

    The transmission of each TCP packet segment is considered successful only after the receiver replies to it

  2. Timeout retransmission

    After sending a packet segment, the sender starts the timer. If no reply is received within the specified time, the sender resends the packet segment.

    To ensure no packet loss, TCP assigns a sequence number to each packet, and the sequence number also ensures that the packets sent to the receiving entity are received in order. The receiving entity then sends back an acknowledgment (ACK) that the packet has been successfully received; If the sending entity does not receive an acknowledgement within a reasonable round trip delay (RTT), the corresponding packet is assumed to be lost and will be retransmitted.

  3. Error checking

    It is calculated by the sender and verified by the receiver. The purpose is to check whether the data has changed between the sender and the receiver. If the receiver detects an error in the checksum, it dismisses the packet directly.

  4. Flow control and blocking management

    Flow control is used to prevent the host from sending too fast for the receiver to fully receive.

1.3 Advantages and disadvantages of TCP

Advantages:

  • Reliable and stable
  • Suitable for transferring large amounts of data

Disadvantages:

  • Slow transmission speed
  • High system resources are occupied

1.4 Differences between TCP and UDP

  1. TCP connection-oriented; UDP is connection-oriented;
  2. TCP provides reliable data transmission, that is, the data transmitted through TCP connection, no error, no loss, no repetition, and in order to arrive; UDP does not guarantee reliable data transmission and is prone to packet loss.
  3. TCP requires a low transmission speed, while UDP does not require a high transmission speed
  4. TCP does not support broadcast. UDP supports broadcast
  5. TCP requires more system resources, while UDP requires less system resources.
  6. TCP is suitable for sending large amounts of data, and UDP is suitable for sending small amounts of data
  7. TCP has traffic control, while UDP does not

1.5TCP Usage Scenarios

When the network communication quality is required, for example, the whole data must be accurately transmitted to the other party. This is usually used for some reliable applications, such as FILE transfer protocols such as HTTP, HTTPS, FTP, and mail transfer protocols such as POP and SMTP.

In daily life, the TCP protocol is used in the following ways:

  • The browser
  • QQ file transfer

1.6UDP Network program flow

A UDP network program sends data without establishing a connection

1.7TCP Network program flow

TCP networking programs need to establish connections to send data

TCP client

2. TCP client code

Example code:

# -*- coding: utf-8 -*-
import socket

# Create TCP socket
tcp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Destination information
server_ip = input("Please enter server IP :")
server_port = int(input("Please enter server port:"))

# Link to server
tcp_client_socket.connect((server_ip, server_port))

# Prompt the user to enter data
send_data = input("Please enter the data you want to send:")
# Send data
tcp_client_socket.send(send_data.encode("gbk"))

# Receive data sent by the other party. The maximum number of bytes can be 1024
recvData = tcp_client_socket.recv(1024)
print('The data received is :', recvData.decode('gbk'))

Close the socket
tcp_client_socket.close()
Copy the code

Running result:

TCP client:

Please enter server IP:127.0. 01.Please enter server port:8080Please enter the data to send: Hey, Lao Song received the data: Hey, Lao WangCopy the code

Network Debugging Assistant:

3. TCP server

TCP server

To complete the function of a TCP server, the process is as follows:

  1. Socket Creates a socket
  2. Bind Binds the IP address and port
  3. Listen converts a socket to passive linking
  4. Accept waits for the client’s link
  5. Recv/SEND Receiving and sending data

A very simple TCP server is as follows:

import socket

# to create a socket
tcp_server_socket = socket(socket.AF_INET, socket.SOCK_STREAM)

# Local information
address = (' '.9090)

# binding
tcp_server_socket.bind(address)


# Set listener
# The default property of a socket created with socket is active. Using Listen makes it passive, so it can accept links from others
# 128: indicates the maximum number of waiting connections
tcp_server_socket.listen(128)

If there is a new client connecting to the server, a new socket will be created to serve that client
# client_socket is used to serve this client
# tcp_server_socket saves you from waiting for other new clients to connect
client_socket, clientAddr = tcp_server_socket.accept()

# Receive the data sent by the other party
recv_data = client_socket.recv(1024)  # Receive 1024 bytes
print('The data received is :', recv_data.decode('gbk'))

Send some data to the client
client_socket.send("thank you !".encode('gbk'))

# Close the socket that serves this client. If it is closed, it means that it can no longer serve this client. If it needs to be served, it must reconnect again
client_socket.close()
Copy the code

Running result:

TCP server

The received data is: Are you there?Copy the code

Network Debugging Assistant:

4. Note points of TCP

  1. Generally, the TCP server must be bound to a port number. Otherwise, the client cannot find the server
  2. Generally, TCP clients are not bound to port numbers. A randomly generated port number is used
  3. Listen allows TCP servers to turn active sockets created by sockets into passive sockets. This is what TCP servers must do
  4. TCP can send and receive data only when a connection is established between the client and the server. Udp can send data directly without establishing a connection
  5. When a TCP client connects to a server successfully, the server will have a new socket. This socket is used to mark the client and serve the client alone
  6. The socket after LISTEN is a passive socket used to receive a new client’s link request, while the new socket returned by Accept marks the new client
  7. Closing a socket after LISTEN means that the passive socket is closed, which causes new clients to be unable to connect to the server, but previously connected clients can communicate.
  8. Closing the socket returned by Accept means that the client is finished serving
  9. When the client socket is called close, the server recv is unblocked and returns a length of 0, so the server can tell whether the client is offline by the length of the data returned

5. TCP three-way handshake

Flowchart of the TCP three-way handshake

Sign a

ACK: indicates the connection. FIN: indicates the connection is closed. Seq: indicates the packet number

Summary:

  1. First handshake: The Client sets the SYN flag bit to 1, generates a value seq=J randomly, and sends the packet to the Server. The Client enters the SYN_SENT state and waits for the Server to confirm.
  2. Second handshake: After receiving the packet, the Server knows that the Client requests to set up a connection by the flag bit SYN=1. The Server sets both the flag bit SYN and ACK to 1, ACK (number)=J+1, randomly generates a value seq=K, and sends the packet to the Client to confirm the connection request. The Server enters the SYN_RCVD state.
  3. The third handshake: After receiving the acknowledgement, the Client checks whether the ACK is J+1 and ACK is 1. If it is correct, the ack flag bit is set to 1 and ACK =K+1 and the packet is sent to the Server. The Server checks whether the ACK is K+1 and ACK is 1. The Client and Server enter the ESTABLISHED state and complete the three-way handshake. Then data transmission between the Client and Server starts.

6. TCP’s 4 waves

TCP 4-wave flow chart

summary

  1. First wave: The Client sends a FIN to close data transfer from the Client to the Server.
  2. Second wave: After receiving the FIN, the Server sends an ACK to the Client. The ACK number is +1.
  3. Third wave: The Server sends a FIN to shut down data transfer from the Server to the Client.
  4. Fourth wave: After receiving the FIN, the Client sends an ACK to the Server. The ACK number is +1.

conclusion

This is a long article, give a big thumbs-up to those who see it! Due to the limited level of the author, it is inevitable that there will be mistakes in the article, welcome feedback and correction.

If you think the article is helpful to you, please like, comment, and collect

Your support is my biggest motivation!!