大模型免费的
import socket
import threading
import time
from queue import Queue
# 存储用户信息
users = {}
# 用户消息队列
message_queue = Queue()
# 扫描文件线程
def scan_file():
while True:
with open('external.txt', 'r') as file:
lines = file.readlines()
for line in lines:
if line.strip(): # 忽略空行
parts = line.split(':')
if len(parts) == 2:
user, message = parts[0].strip(), parts[1].strip()
message_queue.put((user, message))
time.sleep(1) # 每秒检查一次文件
# 处理客户端连接
def handle_client(client_socket, address):
print(f"Connected by {address}")
try:
# 接收用户名
username = client_socket.recv(1024).decode('utf-8').strip()
users[username] = client_socket
print(f"User {username} joined.")
while True:
# 从消息队列中获取消息并发送给特定用户或所有用户
if not message_queue.empty():
target_user, message = message_queue.get()
if target_user == "all":
broadcast(message)
elif target_user in users:
send_message(target_user, message)
# 接收客户端的消息
data = client_socket.recv(1024)
if not data:
break
message = data.decode('utf-8')
print(f"Received from {username}: {message}")
# 存储消息
with open(f"{username}_messages.txt", 'a') as f:
f.write(f"{message}\n")
except Exception as e:
print(f"Error handling client: {e}")
finally:
# 移除用户
del users[username]
client_socket.close()
print(f"User {username} disconnected.")
# 广播消息给所有用户
def broadcast(message):
for user, conn in users.items():
send_message(user, message)
# 向特定用户发送消息
def send_message(user, message):
if user in users:
users[user].sendall(message.encode('utf-8'))
# 主函数
def main():
host = '127.0.0.1'
port = 65432
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen(50) # 最大监听数为50个连接
print("Server started on port 65432")
# 启动文件扫描线程
threading.Thread(target=scan_file, daemon=True).start()
try:
while True:
client_socket, addr = server.accept()
threading.Thread(target=handle_client, args=(client_socket, addr
)).start()
except KeyboardInterrupt:
print("Server shutting down.")
server.close()
if __name__ == "__main__":
main()
【 在 zqhl 的大作中提到: 】
: 写一个socket服务器端,要求
: 1 能够链接五十个用户
: 2 和用户连接后永不关闭,随时和用户进行通信
: ...................
--
修改:ae175b1bf388 FROM 114.253.35.*
FROM 114.253.35.*