我几乎阅读了互联网上的每篇文章,但似乎对我的情况没有任何帮助。我已经安装了flask-socketio,并且一切正常,直到我从app.py以外的模块发出消息为止。
我已经尝试了多种方法来实现此目的,并且我还通过使用Redis在文档中阅读了该文档,但是它对我也不起作用。这是我的代码片段。
app.py
from flask import Flask
from flask import request
from flask_socketio import send, SocketIO, emit, join_room
app = Flask(__name__)
# This is to stop force sorting in response, by default jsonify sorts the response keys alphabetically
app.config["JSON_SORT_KEYS"] = False
socketio = SocketIO(app, cors_allowed_origins="*")
@socketio.on('join')
def client_join_room(data):
print(type(data))
room = data['room']
join_room(room)
send('you have entered the room.', room=room)
@app.route('/msg')
def send_message():
socketio.emit("message", "Server message", room='my_room')
return "I got you."
if __name__ == '__main__':
socketio.run(host="0.0.0.0", port=5001, debug=True, app=app)
my_module.py
def some_method():
import app
app.socketio.emit("message", "Some information about process", room='my_room', broadcast=True)
请注意,我已经在方法内部导入了应用程序,因为app.py
也导入了my_module.py
我可以加入房间。
当我呼叫localhost:5001 / msg时,它确实会发出到'my_room'。
发射无法在my_module.py内部运行,我也不知道为什么。
我正在安慰从前端服务器收到的消息,因此我可以确定哪些消息是接收的,哪些不是。
此外,此处的some_method()
由来自app.py的API请求调用。万一这是否相关。
我已将logger = True设为True,然后在每次发出呼叫时,都会在终端上打印此消息。即使里面有一个some_method()
将事件“消息”发送到my_room [/]
这是否意味着实际上已发送邮件?如果是,那为什么我在前端的jQuery中没有得到它?
这是我在html页面中所做的
$(document).ready(function () {
// start up the SocketIO connection to the server
var socket = io.connect('http://localhost:5001/');
// this is a callback that triggers when the "message" event is emitted by the server.
socket.on('message', function(msg){
console.log(msg)
});
socket.emit('join', {room: 'my_room'});
});
请尝试安装Redis和eventlet以进行异步调用并从其他模块发送消息。如documentation中所述,您可以将app.py中的行更改为
socketio = SocketIO(app, cors_allowed_origins="*", message_queue='redis://', async_mode='eventlet')