循环似乎打破了命名空间方法中的“发出”事件[gevent-socketio]

时间:2013-09-22 07:28:38

标签: python websocket socket.io gevent gevent-socketio

因为几天我一直试图在服务器端设置某种循环而不成功,这允许我定期更新客户端,但似乎如果你把一个循环放入服务器事件方法,它就会停止自动向客户端发送事件。我的直觉是“gevent”(或greenlets)不允许这种行为(只有客户端,使用socket.io的浏览器可以定期向服务器发出,而不是相反)。我错了吗?你会如何解决这个问题?是否有可能,如果你做一个循环,与客户端(套接字)的连接会以某种方式丢失?我将在模式中添加一个小草稿。

// 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.

谢谢!

1 个答案:

答案 0 :(得分:5)

您需要将time.sleep(3)更改为gevent.sleep(3),这是告诉单个greenlet睡眠的方式。来自docs

  

gevent.sleep(seconds = 0)将当前的greenlet置于至少睡眠状态   秒。

     

秒可以指定为整数,如果是小数则指定为浮点数   需要几秒钟。以秒为单位调用睡眠是规范的   表达合作产量的方式。