实现基于UDp的服务端和客户端
时间: 2023-09-05 21:10:00 浏览: 89
udp通信的服务端和客户端
4星 · 用户满意度95%
UDP(User Datagram Protocol)是一种无连接的、不可靠的传输协议,它不保证数据传输的可靠性和顺序性,但是传输效率高,适用于实时性要求高的场景。下面是基于UDP的服务端和客户端的实现示例:
服务端:
```python
import socket
# 创建UDP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定地址和端口
server_address = ('', 8888)
server_socket.bind(server_address)
print('UDP server is running...')
while True:
# 接收数据
data, client_address = server_socket.recvfrom(1024)
print('Received data from {}: {}'.format(client_address, data.decode()))
# 发送响应数据
response_data = 'Hello, {}'.format(client_address).encode()
server_socket.sendto(response_data, client_address)
```
客户端:
```python
import socket
# 创建UDP套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 发送数据
server_address = ('localhost', 8888)
data = 'Hello, server!'.encode()
client_socket.sendto(data, server_address)
# 接收响应数据
response_data, server_address = client_socket.recvfrom(1024)
print('Received data from {}: {}'.format(server_address, response_data.decode()))
# 关闭套接字
client_socket.close()
```
在运行服务端程序之后,可以使用客户端程序发送数据。服务端程序在接收到数据之后会将其输出,并发送响应数据给客户端。
阅读全文