Question

since a few days I've been unsuccessfully trying to have some kind of loop in the server side that would allow me to update the client periodically, but it seems like if you put a loop into the server event method, it stops emitting events to the client automatically. My gut feeling is that "gevent" (or the greenlets) don't allow this kind of behavior (only the clients, the browsers using socket.io, can emit periodically to the server, not the opposite). Am I wrong? How would you solve this problem? is it possible that if you do a loop the connection with the client (socket) gets lost somehow? I'll attach a small draft with the schema.

// Client (socket.io) [Javascript]

client = io.connect('/space');
client.on('do_something', function (msg) {
    // Do something.
});
client.on('do_another_thing', function (msg) {
   // Do another thing.
});
client.emit('something', msg);


# Server (gevent-socketio) [Python]

@namespace('/space')
class SpaceNamespace:
    def on_something(msg):
        # This WORKS just fine cause it's out the scope of the loop.
        self.emit('do_another_thing', some_operation(msg))
        # This DOES NOT work.
        while True:
            # Each 3 seconds update the client.
            self.emit('do_something', some_operation(msg))
            time.sleep(3)
            # If you put an ipdb here, you can see like the code
            # is executed, but the browser doesn't receive any
            # event.

Thanks!

Était-ce utile?

La solution

You will want to change time.sleep(3) to gevent.sleep(3) which is the way of telling the individual greenlet to sleep. From the docs:

gevent.sleep(seconds=0) Put the current greenlet to sleep for at least seconds.

seconds may be specified as an integer, or a float if fractional seconds are desired. Calling sleep with seconds of 0 is the canonical way of expressing a cooperative yield.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top