title: Starting websocket server in different thread/event loop
body: <p>I'm building a Websocket server application in python 3. I'm using this implementation: <a href="https://websockets.readthedocs.io/" rel="nofollow noreferrer">https://websockets.readthedocs.io/</a></p>
  
  <p>Basically I want to launch the server and client in the same process using different threads.</p>
  
  <p>Here is my code. The server seems to start but the client does not connect.</p>
  
  <p>What am I doing wrong ?</p>
  
  <p>Guillaume</p>
  
  <pre><code>import asyncio
  import websockets
  import socket
  from threading import Thread
  
  async def hello(websocket, path):
      name = await websocket.recv()
      print(f"&lt; {name}")
      greeting = f"Hello {name}!"
      await websocket.send(greeting)
      print(f"&gt; {greeting}")
  
  def start_loop(loop):
      asyncio.set_event_loop(loop)
      loop.run_forever()
  
  # Get host and port from config file
  server_host = socket.gethostname()
  server_port = 8081  # random.randint(10000, 60000)
  
  print('server_host: ' + server_host)
  
  # start a new event loop
  new_loop = asyncio.new_event_loop()
  t = Thread(target=start_loop, args=(new_loop,))
  t.start()
  
  start_server = websockets.serve(hello, server_host, server_port, loop=new_loop)
  
  print("Server launched")
  
  async def hello():
      uri = "ws://{}:{}".format(server_host, server_port)
      async with websockets.connect(uri) as websocket:
          name = input("What's your name? ")
  
          await websocket.send(name)
          print(f"&gt; {name}")
  
          greeting = await websocket.recv()
          print(f"&lt; {greeting}")
  
  asyncio.get_event_loop().run_until_complete(hello())
  </code></pre>