python实现单聊群聊的聊天室
时间: 2023-12-17 18:28:25 浏览: 220
基于python进行开发的聊天室(单聊、群聊、gui界面、自动回复)
3星 · 编辑精心推荐
以下是Python实现单聊和群聊的聊天室的示例代码:
1. 单聊
```python
import socket
# 创建socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 获取本地主机名
host = socket.gethostname()
# 设置端口号
port = 9999
# 绑定端口号
server_socket.bind((host, port))
# 设置最大连接数,超过后排队
server_socket.listen(5)
while True:
# 建立客户端连接
client_socket, addr = server_socket.accept()
print("连接地址: %s" % str(addr))
msg = '欢迎访问菜鸟教程!' + "\r\n"
client_socket.send(msg.encode('utf-8'))
client_socket.close()
```
2. 群聊
```python
import socket
import threading
# 创建socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 获取本地主机名
host = socket.gethostname()
# 设置端口号
port = 9999
# 绑定端口号
server_socket.bind((host, port))
# 设置最大连接数,超过后排队
server_socket.listen(5)
# 客户端列表
client_list = []
# 处理客户端消息
def handle_client(client_socket, addr):
while True:
try:
msg = client_socket.recv(1024).decode('utf-8')
if msg:
print("收到来自%s的消息:%s" % (str(addr), msg))
broadcast(msg, client_socket)
else:
remove(client_socket)
except:
continue
# 广播消息
def broadcast(msg, client_socket):
for client in client_list:
if client != client_socket:
try:
client.send(msg.encode('utf-8'))
except:
client.close()
remove(client)
# 移除客户端
def remove(client_socket):
if client_socket in client_list:
client_list.remove(client_socket)
while True:
# 建立客户端连接
client_socket, addr = server_socket.accept()
client_list.append(client_socket)
print("连接地址: %s" % str(addr))
# 创建新线程来处理客户端消息
client_thread = threading.Thread(target=handle_client, args=(client_socket, addr))
client_thread.start()
```
阅读全文