title: How to thread a mqtt subscription and a socket.io Server
body: <p>I tried to setting up a python application that starts a mqtt subscriptions or publish and at the same time I start up a Socket.io Server. My first attempt was to thread these two task - no problem with the mqtt function but there is no solution for me to starting the Socket.io Server in a thread. Here is some of my code:</p>
  
  <p>mqtt_sub.py</p>
  
  <pre class="lang-py prettyprint-override"><code>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()
  </code></pre>
  
  <p>socket.py</p>
  
  <pre class="lang-py prettyprint-override"><code>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)
  </code></pre>
  
  <p>main.py</p>
  
  <pre class="lang-py prettyprint-override"><code>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()
  </code></pre>
  
  <p>The result of that is a runtime error.</p>
  
  <pre><code>RuntimeError: There is no current event loop in thread 'Thread-2'.
  </code></pre>
  
  <p>I tried to get the socketio to start up in a handler but nothing happens. Is there any other possible solution to my problem. Thanks in advance!</p>