title: Make websocket callback asynchronous with asyncio
body: <p>I am trying to implement a basic websocket client using <a href="https://docs.python.org/3/library/asyncio.html" rel="nofollow noreferrer">asyncio</a> and <a href="https://websockets.readthedocs.io/en/stable/index.html" rel="nofollow noreferrer">websockets</a> with Python 3.5.2.</p>
  
  <p>Basically, I want <code>connect_to_dealer</code> to be a blocking call, but wait for the websocket message on a different thread.</p>
  
  <p>After reading some docs (I have very little exp with Python), I concluded that <code>asyncio.ensure_future()</code> passing a coroutine (<code>listen_for_message</code>) was the way to go.</p>
  
  <p>Now, I get to run <code>listen_for_message</code> on a different thread, but from within the coroutine I can't seem to use <code>await</code> or any other mechanism to make the calls <strong>synchronous</strong>. If I do it, the execution waits forever (it hangs) even for a simple <code>sleep</code>.</p>
  
  <p>I'd like to know what I'm doing wrong.</p>
  
  <pre><code>async def listen_for_message(self, future, websocket):
      while (True):
          try:
              await asyncio.sleep(1) # It hangs here
              print('Listening for a message...')
              message = await websocket.recv() # If I remove the sleep, hangs here
              print("&lt; {}".format(message))
              future.set_result(message)
              future.done()
          except websockets.ConnectionClosed as cc:
              print('Connection closed')
          except Exception as e:
              print('Something happened')
  
  def handle_connect_message(self, future):
      # We must first remove the websocket-specific payload because we're only interested in the connect protocol msg
      print(future.result)
  
  async def connect_to_dealer(self):
      print('connect to dealer')
      websocket = await websockets.connect('wss://mywebsocket'))
      hello_message = await websocket.recv()
      print("&lt; {}".format(hello_message))
      # We need to parse the connection ID out of the message
      connection_id = hello_message['connectionId']
      print('Got connection id {}'.format(connection_id))
      sub_response = requests.put('https://subscribetotraffic{user_id}?connection={connection_id}'.format(user_id='username', connection_id=connection_id), headers=headers)
      if sub_response.status_code == 200:
          print('Now we\'re observing traffic')
      else:
          print('Oops request failed with {code}'.format(code=sub_response.status_code))
      # Now we need to handle messages but continue with the regular execution
      try:
          future = asyncio.get_event_loop().create_future()
          future.add_done_callback(self.handle_connect_message)
          asyncio.ensure_future(self.listen_for_message(future, websocket))
      except Exception as e:
          print(e)
  </code></pre>