from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
# 全局内存存储(重启服务数据清空,适合本地测试)
online_users = set() # 在线用户集合
message_list = [] # 消息列表,每条格式 {"username": "xxx", "content": "xxx"}
# 首页渲染聊天页面
@app.route('/')
def index():
return render_template('index.html')
# 用户登录接口
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
username = data.get("username", "").strip()
if not username:
return jsonify({"code": 1, "msg": "昵称不能为空"})
if username in online_users:
return jsonify({"code": 1, "msg": "该昵称已有人在线,请更换"})
online_users.add(username)
return jsonify({"code": 0, "msg": "登录成功"})
# 获取在线用户+所有消息
@app.route('/get_msg')
def get_msg():
return jsonify({
"online": list(online_users),
"messages": message_list
})
# 发送消息接口
@app.route('/send_msg', methods=['POST'])
def send_msg():
data = request.get_json()
username = data.get("username", "")
content = data.get("content", "").strip()
if username not in online_users or not content:
return jsonify({"code": 1, "msg": "发送失败"})
# 存入消息
message_list.append({
"username": username,
"content": content
})
# 限制消息最多保存100条,防止内存溢出
if len(message_list) > 100:
message_list.pop(0)
return jsonify({"code": 0, "msg": "消息发送成功"})
# 用户退出登录
@app.route('/logout', methods=['POST'])
def logout():
data = request.get_json()
username = data.get("username", "")
if username in online_users:
online_users.remove(username)
return jsonify({"code": 0, "msg": "已退出聊天室"})
if __name__ == '__main__':
# 开启多线程,支持多浏览器同时访问
app.run(debug=True, threaded=True, host="0.0.0.0", port=5000)