<div style="width:100%;padding:20px; height: 250px; background-color: #ffffff; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);">
🌻下面是完整python代码
🐶需要用pip工具 install两个扩展,`flask`跟`flask_socketio`,然后运行`python main.py` 即可,默认端口是5000
![](https://img.kancloud.cn/61/ae/61aeac6a291e75a70c3d188b562617fe_673x129.png)
</div>
*****
```
from flask import Flask, render_template, request
from flask_socketio import SocketIO, join_room, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, cors_allowed_origins="*")
@app.route('/send_messages')
def trigger_send_messages():
message = request.args.get('message') # 获取消息内容
user_id = request.args.get('user_id') # 获取用户ID
socketio.emit('new_msg', message, room=user_id)
return 'Messages sent'
@socketio.on('connect')
def handle_connect():
message = 'Welcome to the server!'
print(message)
socketio.emit('new_msg', message)
@socketio.on('join_room')
def handle_join_room(room):
user_id = room # 获取房间 ID
print(f"User {user_id} joined the room.")
join_room(user_id) # 加入特定的房间
@socketio.on('send_message')
def handle_send_message(message):
user_id = request.sid # 获取房间 ID
print(f"Received message from user {user_id}: {message}")
# 向特定的房间 ID 发送消息
socketio.emit('new_msg', message + "emo", room=user_id)
@socketio.on('send_message_all')
def handle_send_message_all(message):
print(message)
socketio.emit('new_msg', message)
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', debug=True)
```