使用python创建udp
时间: 2024-09-13 09:10:54 浏览: 42
python实现udp传输图片功能
在Python中,你可以使用内置的socket模块来创建和操作UDP套接字。下面是一个简单的例子展示如何创建一个UDP客户端和服务器:
### 创建UDP客户端
```python
import socket
def udp_client(message, host, port):
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
try:
print(f"Sending to {host}:{port}")
sock.sendto(message.encode(), (host, port))
response, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print(f"Received from {addr}: {response.decode()}")
finally:
sock.close()
# 示例:向'localhost'的8888端口发送消息
udp_client("Hello, UDP!", "localhost", 8888)
```
### 创建UDP服务器
```python
import socket
def udp_server(host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP server
sock.bind((host, port)) # listen on given address and port
while True:
data, addr = sock.recvfrom(1024) # receive data and its sender's address
print(f"Received message from {addr}: {data.decode()}")
# process the received data here...
reply = "Message received!" # you can customize this response
sock.sendto(reply.encode(), addr)
# 示例:在'localhost'的8888端口监听并响应
udp_server("localhost", 8888)
```
在这个例子中,服务器会持续监听来自特定主机和端口的数据,并作出回应。客户端则是主动发起数据交换。
阅读全文