线程中的 flask-websocket 发出在不应该广播的时候正在广播

flask-websocket emit in thread is broadcasting when it shouldn't

我有以下线程发送到正在工作的 websocket,但是如果我有两个浏览器 windows(或多个客户端连接),它们都会看到相同的数据被推送。在 https://github.com/miguelgrinberg/Flask-SocketIO 的示例代码中,我什至不需要指定 broadcast=False,但我试过了,它仍然显示在所有连接的 websocket windows.

@socketio.on('job_submit', namespace='/socket')
def job_submit(message):
    emitter('received job')
    # start job and kick off thread to read and emit output of job (setup in redis list)
    job = background_task.delay()
    runme = test_duplicates(message)
    if runme:
        threads[len(threads) + 1] = {'thread': None, 'thread_lock': Lock()}
        global thread
        thread = threads[len(threads)]['thread']
        with threads[len(threads)]['thread_lock']:
            if thread is None:
                thread = socketio.start_background_task(output_puller, job)
        threads[len(threads)]['thread'] = thread
        threads[len(threads)]['thread'].setName(message['data'])


def output_puller(job):
    while job.state != 'SUCCESS' and job.state != 'FAILURE':
        result = r_server.lpop(job.id)
        if result:
            socketio.emit('my_response', {'data': result.decode()}, namespace='/socket', broadcast=False)
            print(result)

我的默认设置是 socket.io 将向所有连接的人广播。如果你想广播给特定的客户端,你需要在连接时获取会话 ID:

下面是烧瓶示例

@io.on('connected')
def connected():
    print "%s connected" % (request.namespace.socket.sessid)
    clients.append(request.namespace)

以及何时发送。

clients[k].emit('message', "Hello at %s" % (datetime.now()))

你告诉它发送给哪个客户端而不是全局发出