0

I have the following thread that emits to the websocket that is working, but if I have two browser windows ( or multiple clients connect) they all see the same data being pushed. In the example code from https://github.com/miguelgrinberg/Flask-SocketIO appears that I shouldn't even need to specify broadcast=False, but I tried it and it still shows up in all connected 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)
user1601716
  • 1,893
  • 4
  • 24
  • 53

1 Answers1

1

My default, socket.io will broadcast to everyone who connects. If you want to broadcast to a specific client, you'll need to grab the session id on connect:

below is a flask example

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

And when you want to send.

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

you tell it which client to send to instead of a global emit

Eric Yang
  • 2,678
  • 1
  • 12
  • 18