udp回显服务端与客户端python
时间: 2023-10-02 19:05:31 浏览: 168
实现方式是什么?
UDP回显服务端与客户端Python实现方式如下:
UDP回显服务端:
```
import socket
serverAddress = ('localhost', 6789)
maxSize = 4096
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serverSocket.bind(serverAddress)
print('UDP回显服务器启动,监听端口:', serverAddress)
while True:
data, clientAddress = serverSocket.recvfrom(maxSize)
print('客户端地址:', clientAddress)
print('接收数据:', data.decode('utf-8'))
serverSocket.sendto(data, clientAddress)
print('回显数据:', data.decode('utf-8'))
```
UDP回显客户端:
```
import socket
serverAddress = ('localhost', 6789)
message = 'Hello, UDP Echo Server!'
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
clientSocket.sendto(message.encode('utf-8'), serverAddress)
print('发送数据:', message)
data, serverAddress = clientSocket.recvfrom(4096)
print('服务器地址:', serverAddress)
print('接收数据:', data.decode('utf-8'))
```
注意:以上代码仅为参考,具体实现方式可以根据实际情况进行调整和优化。
阅读全文