我正在使用https://github.com/miguelgrinberg/Flask-SocketIO开始使用flask和SocketIO。
我想将一个字符串发布到烧瓶服务器,然后通过SocketIO将其发送到客户端网页。
通常我的发布代码如下:
@app.route('/index',methods=['POST'])
def index():
token = request.form['token']
据我了解,需要类似以下内容从服务器向客户端页面发送数据:
@socketio.on('event', namespace='/test')
def test_message(message):
emit('my response', {'data': message['data']}, broadcast=False)
我不清楚如何将2个函数绑定在一起,以便在帖子上将令牌的值发送给客户端。
我在文档中找到的最接近的是:
Receiving Messages¶
When using SocketIO messages are received by both parties as events. On the client side Javascript callbacks are used. With Flask-SocketIO the server needs to register handlers for these events, similarly to how routes are handled by view functions.
我怎样才能使这个工作?
答案 0 :(得分:0)
你的假设是正确的。首先,POST向Flask发送数据:
.ajax({
url: "{{ url_for('index') }}",
method: "POST",
data: {
token: "value"
}
});
您的view看起来像
@app.route('/index',methods=['POST'])
def index():
token = request.form['token']
test_message(dict(data=token))
return '1'
您的JavaScript看起来像
var socket = io.connect('http://' + document.domain + ':' + location.port + namespace);
socket.on('connect', function() {
socket.emit('my event', {data: 'I\'m connected!'});
});
socket.on('my response', function(msg) {
// do something with msg.data
});