Python: TCP protocol

TCP protocol
TCP protocol, Transmission Control Protocol (English: Transmission Control Protocol, abbreviated as TCP) is a connection-oriented, reliable, byte stream-based transport layer communication protocol, defined by RFC 793 of IETF.

TCP communication needs to go through three steps: connection creation, data transmission, and connection termination.

In the TCP communication model, before the communication starts, the relevant link must be established before the data can be sent, which is similar to "calling" in life.

TCP features
The communication parties must first establish a connection to transmit data, and both parties must allocate the necessary system kernel resources for the connection to manage the state of the connection and the transmission on the connection.

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

After completing the data exchange, both parties must disconnect the connection to release system resources.

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

reliable transmission
1) TCP adopts sending response mechanism

Each message segment sent by TCP must be answered by the receiver before the TCP message segment is considered successful.

2) Timeout retransmission

The sender starts the timer after sending a message segment, and resends the message segment if no response is received within the time limit.

In order to ensure that no packet loss occurs, TCP gives each packet a sequence number, and the sequence number also ensures that the packets transmitted to the receiving end entity are received in order. The receiving entity then sends back a corresponding acknowledgment (ACK) for the successfully received packet; if the sending entity does not receive an acknowledgment within a reasonable round-trip delay (RTT), the corresponding packet is assumed to have been received. Lost ones will be retransmitted.

3) Error checking

TCP uses a checksum function to check data for errors; checksums are calculated both when sending and when receiving.

4) Flow control and congestion management

Flow control is used to prevent the host from sending too fast so that the receiver has no time to fully accept it.

The difference between TCP and UDP
Connection-oriented (Confirm that there is a three-way handshake, and the connection is established before transmission.)
Ordered Data Transfer
resend lost packets
discard duplicate packets
Error-free data transmission
blocking/flow control

TCP communication model
In the TCP communication model, before the communication starts, the relevant link must be established before data can be sent

server and client
A server, also called a server, is a device that provides computing services. Since the server needs to respond to and process service requests, generally speaking, the server should have the ability to undertake and guarantee services. Client (Client), also called client, refers to a program that corresponds to a server and provides local services for clients. The client-server architecture is also known as the master-slave architecture, referred to as the C/S structure. It is a network architecture that separates the client from the server. An instance of client software can be sent to a server or application server. ask.

TCP client
Compared with the TCP server, the tcp client is much simpler. If the server needs to buy a mobile phone, check the mobile phone card, set the ringtone, and wait for others to make a call, then the client only needs to find a phone booth and take You can just call on the phone, and the process is much less.

import socket

# Socket connection based on tcp protocol
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Before sending data, you must first establish a connection with the server
s.connect(('', 9090)) # call the connect method to connect to the server
s. send('hello'. encode('utf8'))

# udp directly use sendto to send data
# s.sendto('hello'.encode('utf8'),('',9090))

s. close()
TCP server
In the program, if you want to complete the function of a tcp server, the required process is as follows:
socket creates a socket
bind binds ip and port
listen makes the socket passively connectable
accept waits for the connection from the client
recv/send receives and sends data

import socket

# Create a socket connection
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 9090))

s.listen(128) # Turn the socket into a passive listening socket

# ,
# ('', 38096)
# )
# The received result is a tuple with two elements
# The 0th element is the client's socket connection, and the 1st element is the client's ip address and port number
# x = s.accept() # Receive the client's request

client_socket, client_addr = s. accept()

# Receive data in udp, use recvfrom
data = client_socket.recv(1024) # Use recv to get data in tcp
print('Received the data sent by {}client {} port number, the content is: {}'.format(client_addr[0], client_addr[1], data.decode('utf8')))
Notes on TCP
Generally, the tcp server needs to be bound, otherwise the client cannot find the server
The tcp client is generally not bound, because it is actively connected to the server, so as long as the server's ip, port and other information are determined, the local client can be randomly connected
In the tcp server, the active socket created by the socket can be changed to passive through listen, which must be done when doing a tcp server
When the client needs to connect to the server, it needs to use connect to connect. UDP does not need to connect but sends it directly, but tcp must connect first. Only when the connection is successful can communication
When a tcp client connects to the server, there will be a new socket on the server side, which is used to mark the client and serve the client alone
The socket after listen is a passive socket, which is used to receive the connection request of the new client, and the new socket returned by accept marks the new client
Closing the socket after listening means that the passive socket is closed, which will cause new clients to be unable to connect to the server, but clients that have successfully connected before communicate normally.
Closing the socket returned by accept means that the client has been served
When the client's socket calls close, the server will recv unblock it, and the length returned is 0, so the server can distinguish whether the client has gone offline by the length of the returned data

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00

phone Contact Us