0

I've implemented webSocket server in python using built-in libraries like WebSocketServerFactory as shown in the following code :

from autobahn.asyncio.websocket import WebSocketServerProtocol, WebSocketServerFactory
import ssl

import asyncio


sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
sslcontext.load_cert_chain(self.sslcert, self.sslkey)

factory = WebSocketServerFactory(u"{0}://127.0.0.1:{1}".format(ws, self.port))
factory.protocol = ResourceProtocol

loop = asyncio.get_event_loop()

coro = loop.create_server(factory, '', self.port, ssl=sslcontext)
self.server = loop.run_until_complete(coro)

I wonder if I can add another server with the event_loop that will run simple http server to accept GET/POST requests ?

Zohar81
  • 4,554
  • 5
  • 29
  • 82
  • Any reason not to use a common web framework like Flask or FastAPI? – flakes Nov 28 '21 at 19:18
  • Hi, thanks for the comment. perhaps can you refer me to an example of websocket and http server implemented in one of those frameworks ? – Zohar81 Nov 28 '21 at 19:19
  • Try here: https://fastapi.tiangolo.com/advanced/websockets I've been using FastAPI for a while now with a lot of success. – flakes Nov 28 '21 at 19:22
  • it's indeed seems much easier to implement... But i cannot see how to add the ssl layer to my websocket and http handlers. Perhaps do you have some experience in adding it ? – Zohar81 Nov 28 '21 at 19:28
  • You launch the application with `uvicorn`. Just pass the appropriate flags. https://www.uvicorn.org/settings/#https – flakes Nov 28 '21 at 19:31
  • Thanks a lot, I've managed to add the ssl layer. Just one more question... in the websocket handler, I'd like to add multiple async functions (i.e. one that wait for input from the client, another that trigger data send to the client when a file created, etc...) do you how can I run multiple async functions in parallel ? – Zohar81 Nov 28 '21 at 20:47

1 Answers1

0

Theoretically it should be possible.

You may use

asyncio.gather() allows to wait on several tasks at once.

E.g. Running a websocket server (autobahn) with aiohttp http server

# websocket server autobahn
coro = loop.create_server(factory, '', self.port, ssl=sslcontext)

# http server using aiohttp
runner = aiohttp.web.AppRunner(app)
loop.run_until_complete(runner.setup())
site = aiohttp.web.TCPSite(runner)        

server = loop.run_until_complete(asyncio.gather(coro, site.start()))
loop.run_forever()

Or you can use the loop.run_until_complete() function twice for both functions to complete.

Note: I haven't tested this code.

Dhiraj Dhule
  • 1,333
  • 1
  • 9
  • 6