python UDP报文
时间: 2023-11-20 20:57:41 浏览: 128
UDP是一种无连接的传输协议,它不保证数据传输的可靠性,但是传输速度快。在Python中,可以使用socket库来实现UDP报文的发送和接收。下面是一个简单的UDP客户端和服务器端的示例代码:
UDP服务器端代码:
```python
import socket
# 创建UDP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定IP地址和端口号
server_address = ('localhost', 8888)
server_socket.bind(server_address)
# 接收数据
while True:
data, client_address = server_socket.recvfrom(1024)
print('received {} bytes from {}'.format(len(data), client_address))
print(data.decode())
# 发送响应数据
response = 'Hello, client!'
server_socket.sendto(response.encode(), client_address)
```
UDP客户端代码:
```python
import socket
# 创建UDP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 发送数据
server_address = ('localhost', 8888)
message = 'Hello, server!'
client_socket.sendto(message.encode(), server_address)
# 接收响应数据
data, server_address = client_socket.recvfrom(1024)
print('received {} bytes from {}'.format(len(data), server_address))
print(data.decode())
# 关闭socket
client_socket.close()
```
在上面的示例代码中,服务器端首先创建了一个UDP socket,并将其绑定到本地IP地址和端口号。然后,服务器端进入一个无限循环,不断接收客户端发送的数据,并发送响应数据。客户端首先创建了一个UDP socket,并向服务器端发送数据。然后,客户端接收服务器端发送的响应数据。
阅读全文