python聊天室私聊群聊
时间: 2023-12-27 17:25:15 浏览: 82
python聊天室
4星 · 用户满意度95%
以下是一个基于Python实现的简单聊天室的例子,可以实现私聊和群聊功能:
```python
import socket
import threading
# 创建一个socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定IP地址和端口号
server_socket.bind(('localhost', 8888))
# 监听客户端连接
server_socket.listen(5)
# 存储客户端连接的列表
clients = []
def handle_client(client_socket, addr):
while True:
try:
# 接收客户端发送的消息
data = client_socket.recv(1024).decode('utf-8')
if not data:
break
# 判断消息类型,私聊还是群聊
if data.startswith('@'):
# 私聊消息
recipient, message = data.split(':', 1)
for client in clients:
if client[1] == recipient:
client[0].send(f'私聊消息:{message}'.encode('utf-8'))
break
else:
# 群聊消息
for client in clients:
if client[0] != client_socket:
client[0].send(f'群聊消息:{data}'.encode('utf-8'))
except Exception as e:
print(f'Error: {e}')
break
# 关闭客户端连接
client_socket.close()
while True:
# 接受客户端连接
client_socket, addr = server_socket.accept()
# 将客户端连接添加到列表中
clients.append((client_socket, addr[0]))
# 创建一个线程处理客户端连接
client_thread = threading.Thread(target=handle_client, args=(client_socket, addr[0]))
client_thread.start()
```
阅读全文