python 写udp通信代码例子
时间: 2024-11-24 19:39:55 浏览: 3
FPGA udp通信verilog代码+python上位机代码
4星 · 用户满意度95%
在Python中,你可以使用`socket`模块来编写UDP(User Datagram Protocol)通信的代码。下面是一个简单的UDP客户端和服务器的例子:
**服务器端(udp_server.py):**
```python
import socket
def udp_server():
# 创建一个UDP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定IP地址和端口
server_address = ('localhost', 12345) # 修改为你想要监听的地址和端口号
server_socket.bind(server_address)
print(f"Server started on {server_address[0]}:{server_address[1]}")
while True:
# 接收数据并回应
data, client_address = server_socket.recvfrom(4096) # 设置接收缓冲区大小
received_data = data.decode('utf-8')
print(f"Received message from {client_address}: {received_data}")
response = "Message received!"
server_socket.sendto(response.encode(), client_address)
if __name__ == "__main__":
udp_server()
```
**客户端(udp_client.py):**
```python
import socket
def udp_client(message):
# 创建一个UDP套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 发送数据到服务器
server_address = ('localhost', 12345) # 修改为你服务器的IP和端口号
client_socket.sendto(message.encode(), server_address)
# 接收服务器响应
data, server_address = client_socket.recvfrom(4096)
received_data = data.decode('utf-8')
print(f"Response from server: {received_data}")
if __name__ == "__main__":
message = input("Enter a message to send: ")
udp_client(message)
```
运行这两个脚本,一个作为服务器启动,另一个作为客户端连接。客户端发送消息,服务器接收后返回响应。
阅读全文