ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-08-31 14:05:47  阅读:171  来源: 互联网

标签: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.

谢谢!

解决方法:

您需要将time.sleep(3)更改为gevent.sleep(3),这是告诉单个greenlet睡眠的方式.从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,websocket,socket-io,gevent,gevent-socketio
来源: https://codeday.me/bug/20190831/1776222.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有