用python编写UDP通信服务器与客户端
时间: 2023-05-31 16:04:25 浏览: 130
UDP通信服务器与客户端的Python代码示例:
服务器端代码:
```python
import socket
# 创建UDP套接字
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(f"Received data: {data.decode('utf-8')} from {client_address}")
response = "Hello, client!"
server_socket.sendto(response.encode('utf-8'), client_address)
```
客户端代码:
```python
import socket
# 创建UDP套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 发送数据
server_address = ('localhost', 8888)
message = "Hello, server!"
client_socket.sendto(message.encode('utf-8'), server_address)
# 接收回复
data, server_address = client_socket.recvfrom(1024)
print(f"Received data: {data.decode('utf-8')} from {server_address}")
```
在运行服务器端代码之前,需要先运行客户端代码,因为客户端会先向服务器发送数据,服务器才会回复。
阅读全文