gpt4 book ai didi

python - 循环似乎打破了命名空间方法中的 "emit"事件 [gevent-socketio]

转载 作者:太空宇宙 更新时间:2023-11-03 14:27:02 25 4
gpt4 key购买 nike

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

谢谢!

最佳答案

您需要将 time.sleep(3) 更改为 gevent.sleep(3),这是告诉单个 greenlet sleep 的方式。来自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.

关于python - 循环似乎打破了命名空间方法中的 "emit"事件 [gevent-socketio],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18941420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com