用python写一个多人聊天室客户端和服务端的代码,要求能实现文件传输和实时查看在线人数
时间: 2024-03-12 11:47:55 浏览: 105
好的,以下是一个简单的多人聊天室客户端和服务端的Python代码,满足您的要求。其中使用了socket、select、threading等模块实现。
服务端代码:
```python
import socket
import select
import threading
HOST = '127.0.0.1'
PORT = 8888
MAX_CLIENTS = 10
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(MAX_CLIENTS)
clients = []
clients_lock = threading.Lock()
def broadcast(message, sender):
with clients_lock:
for client in clients:
if client != sender:
try:
client.send(message)
except:
clients.remove(client)
def handle_client(client_socket, addr):
with clients_lock:
clients.append(client_socket)
while True:
try:
message = client_socket.recv(1024)
if message:
broadcast(message, client_socket)
else:
raise Exception('Client disconnected')
except:
with clients_lock:
clients.remove(client_socket)
client_socket.close()
return
def count_online():
while True:
with clients_lock:
online_num = len(clients)
print('Online: {}'.format(online_num))
for client in clients:
try:
client.send(('Online: {}\n'.format(online_num)).encode())
except:
clients.remove(client)
threading.Event().wait(5)
count_thread = threading.Thread(target=count_online)
count_thread.daemon = True
count_thread.start()
while True:
client_socket, addr = server_socket.accept()
threading.Thread(target=handle_client, args=(client_socket, addr)).start()
```
客户端代码:
```python
import socket
import select
import threading
import sys
import os
HOST = '127.0.0.1'
PORT = 8888
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
def receive():
while True:
try:
message = client_socket.recv(1024)
if message:
sys.stdout.write(message.decode())
sys.stdout.flush()
else:
raise Exception('Server disconnected')
except:
client_socket.close()
os._exit(0)
def send():
while True:
message = sys.stdin.readline()
if message.strip() == '':
continue
client_socket.send(message.encode())
def file_send():
while True:
message = sys.stdin.readline().strip()
if message == '':
continue
try:
filename = message.split()[-1]
with open(filename, 'rb') as f:
client_socket.send('file {}'.format(os.path.basename(filename)).encode())
client_socket.send(f.read())
except:
print('File not found')
receive_thread = threading.Thread(target=receive)
receive_thread.daemon = True
receive_thread.start()
send_thread = threading.Thread(target=send)
send_thread.daemon = True
send_thread.start()
file_thread = threading.Thread(target=file_send)
file_thread.daemon = True
file_thread.start()
while True:
pass
```
客户端支持文件传输,发送文件时输入文件名即可,服务端会自动转发给所有客户端。同时客户端也支持实时查看在线人数,服务端会每隔5秒广播当前在线人数给所有客户端。
阅读全文