Python socketio,在后台运行socketio服务器
如何启动 SocketIO 服务器并让它在后台监听,同时继续在主线程上执行代码?
现在我正在使用包python-socketio
。我还测试了使用 python-socketio 的flask-socketio
。
https://python-socketio.readthedocs.io/en/latest/server。 html
我主要尝试的是使用 sio.start_background_task 启动服务器。
例如:
class SocketIOServer(socketio.AsyncNamespace):
def __init__(self):
super().__init__()
self.sio = socketio.AsyncServer()
self.sio.register_namespace(self)
self.app = web.Application()
self.sio.attach(self.app)
self.task = None
def run(self):
web.run_app(self.app, port=8080)
def start(self):
self.task = self.sio.start_background_task(self.run)
我尝试了上述方法和多种变体,例如使用 Flask、Tornado 等。
更清楚地说,这基本上就是我想做的:
if __name__ == '__main__':
# ...
# start app, e.g. -> web.run_app(self.app, port=8080)
# I want to continue to execute code here
我不完全理解一切是如何工作的,我是在问一个愚蠢的问题吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如您所描述的那样。您不完全了解一切的运作方式。
您缺少的最重要的是Python-Socketio软件包不是Web服务器。该软件包只会实现socket.io逻辑,但是您必须添加一个可以通过socket.io代码的Web服务器。
从您的问题中包含的代码中,您似乎已经选择将socket.io代码连接到使用AIOHTTP框架构建的Web应用程序,并使用自己的Web服务器。正确的?
然后,您遇到的真正问题是如何以非阻滞方式运行AIOHTTP Web服务器。
而且已经用AIOHTTP在其文档中具有有关此信息的信息:。他们这样做的例子:
The problem is as you described it. You do not fully understand how everything works.
The most important thing that you are missing is that the python-socketio package is not a web server. This package just implements the Socket.IO logic, but you have to add a web server through which your Socket.IO code is available.
From the code that you included in your question, it appears that you have selected to attach the Socket.IO code to a web application built with the aiohttp framework, and use its own web server. Correct?
Then the real question that you have is how to run the aiohttp web server in a non-blocking way.
And it runs out that aiohttp has information on this in their documentation: https://docs.aiohttp.org/en/stable/web_advanced.html#application-runners. The example they have does this: