用python写一个多人聊天室代码
时间: 2024-03-09 11:03:05 浏览: 88
python实现多人聊天室
以下是一个简单的 Python 多人聊天室代码,基于 socket 和 threading 模块:
```python
import socket
import threading
# 服务器地址和端口号
HOST = 'localhost'
PORT = 8888
# 创建一个 socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen()
clients = []
def handle_client(client_socket, client_address):
while True:
try:
# 接收数据
data = client_socket.recv(1024).decode('utf-8')
if data:
# 广播消息
message = f"{client_address[0]}:{client_address[1]} says {data}"
print(message)
broadcast(message, client_socket)
else:
# 移除客户端
remove(client_socket)
except:
# 移除客户端
remove(client_socket)
break
def broadcast(message, sender):
for client in clients:
if client != sender:
client.send(message.encode('utf-8'))
def remove(client_socket):
if client_socket in clients:
clients.remove(client_socket)
client_socket.close()
while True:
# 接受客户端连接
client_socket, client_address = server_socket.accept()
print(f"Connected with {client_address[0]}:{client_address[1]}")
clients.append(client_socket)
# 创建线程处理客户端请求
client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
client_thread.start()
```
使用该代码,可以在终端启动服务器,并监听来自多个客户端的连接。运行该代码后,可以使用 telnet 或者其他 TCP 客户端连接到服务器,进行聊天。
阅读全文