python Socket编写UDP聊天室
时间: 2023-06-30 11:22:36 浏览: 130
以下是一个简单的UDP聊天室的Python Socket程序:
服务端代码:
```python
import socket
# 创建UDP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定地址和端口
server_address = ('localhost', 8888)
server_socket.bind(server_address)
# 接收客户端消息并广播
while True:
message, address = server_socket.recvfrom(1024)
print("{} says: {}".format(address, message.decode()))
server_socket.sendto(message, address)
```
客户端代码:
```python
import socket
# 创建UDP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 获取服务端地址和端口
server_address = ('localhost', 8888)
# 循环发送消息
while True:
# 输入消息
message = input('Please input message: ')
# 发送消息
client_socket.sendto(message.encode(), server_address)
# 接收消息
message, address = client_socket.recvfrom(1024)
print("Server says: {}".format(message.decode()))
```
在运行程序之前,需要先在命令行中启动服务端程序,然后再启动多个客户端程序。每个客户端程序就可以发送消息到服务端,并且可以收到其他客户端发送的消息。
阅读全文