繁体   English   中英

使用 socketIO 显示客户端值

[英]Displaying client side values with socketIO

我正在使用https://github.com/miguelgrinberg/Flask-SocketIO开始使用 Flask 和 SocketIO。

在此处输入图片说明

我想将一个字符串发布到烧瓶服务器,然后通过 SocketIO,将其发送到客户端网页。

我正在使用邮递员发布令牌值。 请看截图。

我的烧瓶服务器看起来像:

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/ul')
def ul_connect():

    # print('here is ul '+ul)
    print('Client connected')

@app.route('/posting',methods=['POST'])
def posting():
        token = request.form['token']
        test_message(dict(data=token))
        return '1'

@socketio.on('posting', namespace='/ul')
def test_message(message):
    socketio.emit('response', {'data': message['data']}, broadcast=False)


@socketio.on('disconnect', namespace='/ul')
def ul_disconnect():
    print('Client disconnected')

if __name__ == '__main__

我的客户网页包含:

$(document).ready(function(){
//connect to the socket server.
var namespace = 'http://' + document.domain + ':' + location.port + '/ul';
var socket = io.connect(namespace);
console.log('namespace ',namespace)


//var socket = io.connect('http://' + document.domain + ':' + location.port + namespace);
socket.on('connect', function() {
    socket.emit('my event', {data: 'I\'m connected!'});
});
socket.on('response', function(msg) {
    // do something with msg.data
    console.log('response', msg.data)
});

当我发布令牌时,我在控制台中什么也看不到。 我究竟做错了什么?

如果我理解你的例子,你正在以一种无效的方式混合 Flask/HTTP 和 Socket.IO 数据。

您的第一个问题是识别发送 POST 请求的用户,以便您可以找到他/她的 Socket.IO 连接。 这说起来容易做起来难,HTTP 请求和 Socket.IO 连接之间没有连接,因此您必须在双方添加某种身份验证,或者如果您喜欢更简单的东西,只需记录用户的REMOTE_ADDR (即并不总是可靠的)。

因此,第一步是跟踪通过 Socket.IO 连接的用户(为简单起见,我将使用远程地址):

socketio_clients = {}

@socketio.on('connect', namespace='/ul')
def ul_connect():
    socketio_clients[request.remote_addr] = request.namespace
    print('Client connected')

@socketio.on('disconnect', namespace='/ul')
def ul_disconnect():
    del socketio_clients[request.remote_addr]
    print('Client disconnected')

现在在您的POST请求中,您可以找到用户并发出一条消息:

@app.route('/posting',methods=['POST'])
def posting():
    token = request.form['token']
    client_namespace = socketio_clients.get(request.remote_addr)
    if client_namespace:
        client_namespace.emit('response', {'data': token}))
        return '1'
    abort(400)  # client does not have a socket connection active

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM