python foundation - TCP protocol and UDP protocol

Keywords: Python socket Programming network

TCP is a streaming protocol, UDP is a packet protocol.

TCP and UDP are transport layer protocols in OSI model. TCP provides reliable communication transmission, while UDP is often used to let the broadcast and details control the application's communication transmission.

Summary of differences between TCP and UDP:

TCP UDP
Is it connected? Connection oriented Connectionless
Transmission reliability reliable Unreliable
Application occasion Small amount of data Mass data
transmission speed slow fast

Supplementary description of differences:

1. TCP provides reliable services, and the data transmitted through the TCP connection is error free, not lost, not repeated, and arrives in sequence; UDP tries its best to deliver, and does not guarantee reliable delivery

2. TCP is oriented to byte stream, in fact, TCP regards data as a series of unstructured byte stream; UDP is oriented to message, UDP has no congestion control, so network congestion will not reduce the sending rate of the source host (very useful for real-time applications, such as IP phone, real-time video conference, etc.)

3. Each TCP connection can only be point-to-point; UDP supports one-to-one, one to many, many to one and many to many interactive communication

4. The overhead of TCP header is 20 bytes; the overhead of UDP header is small, only 8 words

Different python programming steps

The general steps on the server side of TCP programming are:

import socket
# Parameters of step 2
from socket import SOL_SOCKET
from socket import SO_REUSEADDR

# TCP server
# 1. Create a socket object and get it through socket()
server_socket = socket.socket()
# 2,Set up socket Properties, importing parameters, via setsockopt() #This step is optional
server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
# 3. Bind the IP address and port information to the socket object. The parameter is a tuple through bind()
server_socket.bind(('127.0.0.1', 9527))
# 4. Open the half connection pool, and use listen(). The parameter is integer, which means receiving the waiting client
server_socket.listen(5)
while True:
    # 5. Blocking status, automatically receiving the connection of the client, and returning the connection object and the client address through the function accept()
    conn, client = server_socket.accept()
    while True:
        try:
            # 6. Receive and send data through recv(). The default parameter is 1024, which means the maximum number of bytes received each time is 1024; 
            re_data = conn.recv(1024).decode('utf-8')
            # After getting the empty data, send and receive the data again
            if len(re_data) == 0:
                continue
            # After getting q, close the connection
            if re_data == 'q':
                break
            print(re_data)
            # send() send data, data must be of type bytes
            msg = input("from server......").strip().encode('utf-8')
            conn.send(msg)
        except ConnectionResetError as e:
            print(e)
    # 7. Close the connection
    conn.close()
    # 8. Close the connection pool
    server_socket.close()

The general steps of TCP programming client are:

import socket
# Parameters of step 2
from socket import SOL_SOCKET
from socket import SO_REUSEADDR

# TCP Client
# 1. Create a socket object and get it through socket()
client_socket = socket.socket()
# 2,Set up socket Properties, importing parameters, via setsockopt() #This step is optional
client_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
# 3. Set the IP address and port properties of the server to be connected and connect to the server through connect()
# The parameter is a tuple. The first element in the tuple is the IP address and the second element is the port number
client_socket.connect(('127.0.0.1', 9527))
while True:
    # 4. Send data through send(). The data must be of bytes type
    msg = input('from client......').strip().encode('utf-8')
    client_socket.send(msg)
    # 5. Receive data through recv(). The default parameter is 1024, which means the maximum number of bytes received each time is 1024;
    re_data = client_socket.recv(1024).decode('utf-8')
    if re_data == 'q':
        break
    print(re_data)
# 6. Close network connection
client_socket.close()

The general steps of UDP programming server are as follows:

import socket
# Parameters of step 2
from socket import SOL_SOCKET
from socket import SO_REUSEADDR

# UDP server
# 1. Get the socket object. type=-1 or 1 indicates that the socket type is sock "stream" -- → TCP by default
# type = 2 indicates that the socket type is sock? Dgram ----- → UDP
server = socket.socket(type=2)
# 2,Set up socket Properties, importing parameters, via setsockopt() #This step is optional
server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
# 3. Bind server address and port
server.bind(('127.0.0.1', 9527))
# 4. Cyclic data sending and receiving
while True:
    # Automatic blocking, waiting for client access, receiving client sending data, receiving using recvfrom()
    # The received record is a tuple, which is data and address
    data, addr = server.recvfrom(1024)
    re_data = data.decode('utf-8')
    if len(re_data) == 0:
        continue
    if re_data == 'q':
        break
    # Print received results
    print(f'client_addr:{addr},re_data:{re_data}')
    # Enter the record sent to the client
    msg = input('from Server to Client:').strip().encode('utf-8')
    # sendto is used for sending messages, and the parameters are binary data and address
    server.sendto(msg, addr)
# 5. Close network connection
server.close()

The general steps of UDP programming client are:

import socket
# Parameters of step 2
from socket import SOL_SOCKET
from socket import SO_REUSEADDR

# UDP server
# 1. Get the socket object. type=-1 or 1 indicates that the socket type is sock "stream" -- → TCP by default
# type = 2 indicates that the socket type is sock? Dgram ----- → UDP
client = socket.socket(type=2)
# 2,Set up socket Properties, importing parameters, via setsockopt() #This step is optional
client.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
server_add = '127.0.0.1'  # Server address
# 3. Cyclic data receiving and sending
while True:
    # sendto() is used for sending data, and the parameters are binary data and address
    msg = input('from_udp_client......').strip().encode('utf-8')
    client.sendto(msg, (server_add, 9527))
    # Receive data using recvfrom()
    re_data, addr = client.recvfrom(1024)
    if re_data.decode('utf-8') == 'q':
        break
    print(re_data.decode('utf-8'))
# 4. Close the connection
client.close()

Posted by lovelyvik293 on Fri, 06 Dec 2019 06:36:08 -0800