Home >Backend Development >Python Tutorial >How does Python implement UDP and TCP communication?

How does Python implement UDP and TCP communication?

王林
王林forward
2023-05-08 11:46:071955browse

1. UDP

UDP is a connectionless and unreliable transmission protocol. Compared with TCP, UDP has the advantages of fast data transmission speed and small transmission delay, but it does not guarantee the reliability of the data. Transmission requires the application layer to perform data retransmission, verification and other processing.

The following is a simple UDP sending example code:

import socket

UDP_IP = '127.0.0.1'   # 目标IP地址
UDP_PORT = 5005        # 目标端口号
MESSAGE = b"Hello, World!"   # 要发送的数据

# 创建UDP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 发送数据
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))

# 关闭套接字
sock.close()

The following is a simple UDP receiving example code:

import socket

UDP_IP = '127.0.0.1'   # 监听IP地址
UDP_PORT = 5005        # 监听端口号

# 创建UDP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 绑定套接字到指定IP地址和端口号
sock.bind((UDP_IP, UDP_PORT))

# 接收数据
data, addr = sock.recvfrom(1024)   # 一次最多接收1024字节的数据

print("Received message:", data)

# 关闭套接字
sock.close()

It should be noted that in UDP communication, Due to the size limit of data packets, the sent data may need to be fragmented, and the received data may also need to be cached and spliced ​​to ensure data integrity.

In IPv4 networks, the maximum length of a UDP packet is 64KB (65535 bytes), including the size of the IP header and UDP header. In practical applications, due to limitations of network equipment and operating systems, the size of UDP packets is usually subject to some restrictions. For example, some routers and firewalls may limit the maximum length of UDP packets, and some operating systems may also impose some restrictions on UDP packets.

When using UDP for data transmission, you need to pay attention to the size limit of data packets and try to avoid sending too large data packets. You can use the getsockopt() method to query the system's limit on UDP packet size, for example:

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
max_size = sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
print(f"Max size of UDP packet: {max_size} bytes")

2. TCP

TCP is a reliable, connection-oriented transmission protocol that provides data The reliability and integrity of transmission are guaranteed, but the transmission efficiency is relatively low.

The following is a simple TCP server and client sample code:

TCP server:

import socket

# 设置IP地址和端口号
IP = '127.0.0.1'
PORT = 8888

# 创建TCP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 绑定IP地址和端口号
sock.bind((IP, PORT))

# 开始监听
sock.listen(1)

print(f"Server listening on {IP}:{PORT}...")

# 接受客户端连接
conn, addr = sock.accept()
print(f"Connected by {addr[0]}:{addr[1]}")

# 接收数据
data = conn.recv(1024)
print(f"Received data: {data.decode()}")

# 发送数据
msg = b"Hello, Client!"
conn.sendall(msg)

# 关闭连接
conn.close()

TCP client:

import socket

# 设置IP地址和端口号
IP = '127.0.0.1'
PORT = 8888

# 创建TCP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 连接服务器
sock.connect((IP, PORT))

# 发送数据
msg = b"Hello, Server!"
sock.sendall(msg)

# 接收数据
data = sock.recv(1024)
print(f"Received data: {data.decode()}")

# 关闭连接
sock.close()

Need to pay attention What is important is that in TCP communication, data transmission needs to be carried out through a connection, so the connection needs to be established first, then the data is transmitted, and finally the connection is closed. Since TCP is a connection-oriented transmission protocol, it requires a complex connection establishment process such as a three-way handshake. It is less efficient than UDP, but has higher reliability.

The above is the detailed content of How does Python implement UDP and TCP communication?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete