我尝试设置一个启动mqtt订阅或发布的python应用程序,同时启动Socket.io服务器。我的第一个尝试是将这两个任务线程化-mqtt函数没有问题,但是对我而言,在线程中启动Socket.io Server没有解决方案。这是我的一些代码:
mqtt_sub.py
import paho.mqtt.client as mqtt
import test.constants as constants
MQTT_PATH = "sensor/water/level"
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client.subscribe(MQTT_PATH)
def on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.payload))
def start_mqtt_subs():
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(constants.MQTT_SERVER, constants.MQTT_SERVER_PORT, constants.MQTT_SERVER_KEEPALIVE)
client.loop_forever()
socket.py
from aiohttp import web
import socketio
sio = socketio.AsyncServer(async_mode='aiohttp')
app = web.Application()
sio.attach(app)
async def index(request):
with open('index.html') as f:
return web.Response(text=f.read(), content_type='text/html')
@sio.on('test')
async def print_message(sid, message):
print("Socket ID: " , sid)
print(message)
app.router.add_get('/', index)
def start_socket_server():
web.run_app(app, host='0.0.0.0', port=1986)
main.py
from test.socket import start_socket_server
from test.mqtt_sub import start_mqtt_subs
import threading
def main():
t1 = threading.Thread(target=start_mqtt_subs)
t2 = threading.Thread(target=start_socket_server)
t1.start()
t2.start()
if __name__ == '__main__':
main()
其结果是运行时错误。
RuntimeError: There is no current event loop in thread 'Thread-2'.
我试图让socketio在处理程序中启动,但是没有任何反应。我的问题还有其他可能的解决方法吗?预先感谢!