Python实现UDP
时间: 2024-06-01 21:06:33 浏览: 82
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, address = server_socket.recvfrom(1024)
print('Received message:', data.decode())
server_socket.sendto(b'Hello, client!', address)
```
UDP客户端代码:
```python
import socket
# 创建UDP socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 发送数据给服务器
server_address = ('localhost', 8888)
client_socket.sendto(b'Hello, server!', server_address)
# 接收服务器回复的数据并输出
data, address = client_socket.recvfrom(1024)
print('Received message:', data.decode())
# 关闭socket
client_socket.close()
```
在这个示例中,服务器和客户端都使用了`socket.AF_INET`和`socket.SOCK_DGRAM`来创建UDP socket对象,用`bind()`方法绑定IP地址和端口号,然后通过`recvfrom()`方法接收数据和地址信息,通过`sendto()`方法发送数据和地址信息,最后通过`close()`方法关闭socket。
阅读全文