Python中的主线程与WebSocket线程

时间:2018-08-23 03:23:28

标签: python multithreading websocket python-asyncio

尽管查看了有关异步,线程,队列,进程,协程等的所有问题,但我找不到如何构造代码的方法。 是一个玩具例子,反映了我的问题。

主线程调用:

... 
myClass = MyClass()
answer = myClass.sendAndGetAnswer("Hello how are you ?") 
print(answer) # Should print the answer recieved over webSocket, 
              # for eg "I'm doing well" 
...

我无法触摸上面的代码,我的任务是实现MyClass,以便myClass.sendAndGetAnswer(msg)通过已打开的websocket发送消息并返回答案。因此,只要没有答案,它就会阻塞主线程。另外sendAndGetAnswer(msg)将被调用很多次,因此我需要websocket连接在sendAndGetAnswer(msg)调用之间保持打开状态。

据我了解,websocket使用asyncio,如果我不在并行线程中使用它(由于asyncio.get_event_loop().run_forever()),它将阻塞发生的其他事情

所以我会做:

class MyClass()

   def __init__(self):
      loop = asyncio.new_event_loop()
      t = Thread(target=self.start_loop, args=(loop,))
      t.start()

   def start_loop(self, loop):
      asyncio.set_event_loop(loop)
      loop.run_until_complete(websockets.serve(self.serverHandler, '127.0.0.1', 9999))
      loop.run_forever()

   async def serverHandler(websocket, path):
       ... ?

   def sendAndGetAnswer(self, msg):
       # Send the message & get the answer
       ... ?
       return answer

所以我可以尝试以下方法:

class MyClass()

   def __init__(self):

       self.lastMsg = None

       loop = asyncio.new_event_loop()
       t = Thread(target=self.start_loop, args=(loop,))
       t.start()

   def start_loop(self, loop):
       asyncio.set_event_loop(loop)
       loop.run_until_complete(websockets.serve(self.serverHandler, '127.0.0.1', 9999))
       loop.run_forever()

   async def serverHandler(websocket, path):
       self.ws = websocket
       async for message in websocket:
           self.lastMsg = message

   def sendAndGetAnswer(self, msg):
       # Send the message & get the answer
       self.ws.send(msg)
       while self.lastMsg != None
          pass
       return self.lastMsg

但这肯定不是解决方案。您能帮我为MyClass编写代码吗?

谢谢

0 个答案:

没有答案