3

几天以来,我一直在尝试在服务器端设置某种循环以允许我定期更新客户端,但似乎没有成功,但是如果您将循环放入服务器事件方法中,它似乎会停止向客户端自动。我的直觉是“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.

谢谢!

4

1 回答 1

5

您将需要更改time.sleep(3)gevent.sleep(3)告诉单个greenlet 睡觉的方式。从文档

gevent.sleep(seconds=0) 让当前的 greenlet 至少休眠几秒钟。

如果需要小数秒,可以将秒数指定为整数或浮点数。以秒为 0 调用 sleep 是表达合作收益的规范方式。

于 2013-09-23T16:38:16.377 回答