How to simultaneously listen for websockets messages and send messages when needed

Viewed 148

What I need is basically a websockets message sender, that sends a message whenever asked to while listener prints out the incoming messages.

I've tried for so long and nothing is working as it should.

If you don't come up with websockets solution, anything is good for me

Here is something I made from some code I found. On the other side is just simple echo server:

from websockets import connect
import threading


class EchoWebsocket:
    async def __aenter__(self):
        self._conn = connect("ws://127.0.0.1:50000")
        self.websocket = await self._conn.__aenter__()        
        return self

    async def __aexit__(self, *args, **kwargs):
        await self._conn.__aexit__(*args, **kwargs)

    async def send(self, message):
        await self.websocket.send(message)

    async def receive(self):
        async for message in self.websocket:
            print(message)


async def main():
    async with EchoWebsocket() as echo:
        thread = threading.Thread(target=echo.receive, args=())
        await echo.send("Hello")
        await echo.send("World!")
        

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())```
0 Answers
Related