Python | TCP Protocol

TCP protocol


The 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 the IETF.

TCP communication needs to go through three steps of 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 data can be sent, which is similar to "calling" in life.

TCP features


connection oriented
Both parties must establish a connection before data transmission, and both parties must allocate necessary system kernel resources for the connection to manage the state of the connection and the transmission on the connection.

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

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

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

reliable transmission
1) TCP uses a send-reply mechanism

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

2) Timeout retransmission

The sender starts a timer after sending a segment, and resends the segment if it does not receive a response within the time period.

In order to ensure that no packet loss occurs, TCP gives each packet a sequence number, and the sequence number also ensures the orderly reception of packets transmitted to the receiving entity. 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), then the corresponding packet is assumed to have been Losses will be retransmitted.

3) Error checking

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

4) Flow control and congestion management

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

Difference between TCP and UDP
Connection-oriented (Confirm that a three-way handshake has been created, and the connection is created 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 known as a server, is a device that provides computing services. Since the server needs to respond to the service request and process it, generally the server should have the ability to undertake and guarantee the service. Client (Client), also known as client, refers to the program corresponding to the server that provides local services for clients. Client-server architecture, also known as master-slave architecture, referred to as C/S architecture, 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.
image.png

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 the call process, then the client only needs to find a phone booth and take it. Just make a phone call, 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(('192.168.31.199', 9090)) # Call the connect method to connect to the server
s.send('hello'.encode('utf8'))

# udp send data directly using sendto
# s.sendto('hello'.encode('utf8'),('192.168.31.199',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 bind ip and port
listen makes the socket passively linkable
accept wait for the client's link
recv/send receive and send data

import socket

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

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

# (
# ,
# ('192.168.31.185', 38096)
# )
# The result received is a tuple with two elements in the tuple
# 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 the {}client{} port number, the content is:{}'.format(client_addr[0], client_addr[1], data.decode('utf8')))

TCP Considerations


The tcp server generally needs to be bound, otherwise the client cannot find the server
The tcp client is generally not bound, because it is an active link server, so as long as the ip, port and other information of the server are determined, the local client can randomly
In the tcp server, the active socket created by the socket can be changed into passive through listen, which must be done when it is 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 directly, but tcp must connect first, and communication can only be done if the connection is successful
When a tcp client connects to the server, the server will have a new socket, which is used to mark the client and serve the client alone
The socket after listen is a passive socket, used to receive connection requests from new clients, and the new socket returned by accept is to mark the new client
Closing the listen socket means that the passive socket is closed, which will cause the new client to not be able to connect to the server, but the client that has been successfully connected before can 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 to unblock, and the returned length is 0, so the server can distinguish whether the client has been 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