4

I'm trying to make a non-blocking code with python's asyncio. There are several threads about this topic but I still have not managed to adapt them to the code. This would be a minimal example based on this:

import asyncio
import websockets

async def ws_rec(websocket, path):
    while True:
        data = await websocket.recv()       
        print(data)

start_server = websockets.serve(ws_rec, 'localhost', 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
print("ok")

How could the code be adapted in order to print "ok"? Why do I even need asyncio for this?

Masoud Rahimi
  • 5,785
  • 15
  • 39
  • 67
Christoph Müller
  • 483
  • 1
  • 5
  • 16
  • Running the event loop takes over the calling thread, but asyncio allows you to easily schedule other non-blocking code to run (in fact, that's what it's there for). For example, you can use `asyncio.create_task(your_coroutine())` and define `async def your_coroutine(): print("ok")`. – user4815162342 Jun 04 '19 at 06:41
  • thanks for the fast reply. Unfortunately my code is based on threading. Do I have to rewrite everything to asyncio or is there another option maybe? – Christoph Müller Jun 04 '19 at 06:49
  • Ideally you'd just use asyncio across the board. But if that's not feasible, you can also run the asyncio event loop in a dedicated thread, as described (under option #3) in [this answer](https://stackoverflow.com/a/50522178/1600898). – user4815162342 Jun 04 '19 at 06:58

1 Answers1

0

Thank you very much for the answers. I have found a workaround with simple-websocket

from simple_websocket_server import WebSocketServer, WebSocket

class SimpleEcho(WebSocket):
    def handle(self):
    # echo message back to client
        print(self.data)
        self.send_message(self.data)

    def connected(self):
        print(self.address, 'connected')

    def handle_close(self):
        print(self.address, 'closed')


def run():
    server = WebSocketServer('localhost', 8765, SimpleEcho)
    server.serve_forever()

from threading import Thread

ws_run = Thread(target=run)
ws_run.start()

print("ok")

Right now, this looks like a working solution for me.

Christoph Müller
  • 483
  • 1
  • 5
  • 16