简体   繁体   中英

Flask and socket.io broadcast

I want to use SocketIO to broadcast messages when a certain event on the server happens, right now I use this code

http://pastebin.com/i2jNf1w5

and I call gevent.spawn(loop_send_queued_messages, server) when launching my server

when a client sends data to '/emit' everything works fine:

  • I see the broadcasting message from broadcast
  • I see the broadcast_msg message from broadcast_msg

However, if in another part of the server I import the broadcast function and I use it from some endpoint (for instance after a user sent a file), I only see the first broadcasting message from the call to broadcast , but it seems that the message is not properly added to the queue because broadcast_msg is never called

Could someone tell me the best way to user SocketIO in Flask to do broadcasting from any location in my server code?

[EDIT] Taking into account the comment below, I have this

broadcasting newDatasetAvailable features 4363892432 scripts.socket_routes
127.0.0.1 - - [2013-12-11 15:56:07] "POST /datastore/features HTTP/1.1" 200 115 0.003130
broadcasting msg refreshData 4363648208 socket_routes
127.0.0.1 - - [2013-12-11 15:56:07] "POST /emit HTTP/1.1" 200 115 0.000540
broadcast_msg msg (u'refreshData',)

so one is scripts.socket_routes , the other is socket_routes

the /emit endpoint is defined in the same file as the websocket_queue , and a POST to /datastore uses the broadcast method from another file, and imports it like that:

from scripts.socket_routes import broadcast

where the structure is:

scripts/
    __init__.py
    socket_routes.py # where websocket_queue and broadcast are defined
    dataset_routes.py # where broadcast is imported

This could be a subtle issue with how you are importing the module. Ie you may have the module loaded twice under two different module names and not realize it.

Modify the print in broadcast() like this:

print "broadcasting", name, data, id(websocket_queue), __name__

Make sure that the same id and module name displays when called from the server code as when called when the client sends data.

If the information doesn't match, then this is the likely problem. It is usually caused by relative imports (which are evil). Switch to absolute imports everywhere and that may fix it.

When using Python 2.6 or earlier, I add from __future__ import absolute_import to the top of every module in order to prevent these kinds of problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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