使用Python的socket模块,使用UDP协议完成双向通信套接字的客户端和服务器端编程
时间: 2024-05-15 09:18:54 浏览: 96
好的,这是一个技术问题,我可以回答。您可以参考以下代码实现:
服务器端:
```
import socket
server_ip = "127.0.0.1"
server_port = 8888
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind((server_ip, server_port))
print("Server started")
while True:
message, client_address = server_socket.recvfrom(1024)
print("Received message from {}: {}".format(client_address, message.decode()))
response = input("Enter response: ")
server_socket.sendto(response.encode(), client_address)
```
客户端:
```
import socket
server_ip = "127.0.0.1"
server_port = 8888
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
message = input("Enter message: ")
client_socket.sendto(message.encode(), (server_ip, server_port))
response, server_address = client_socket.recvfrom(1024)
print("Received response from {}: {}".format(server_address, response.decode()))
```
这个例子使用了UDP协议实现了一个简单的双向通信的套接字客户端和服务器端。
阅读全文