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 ?

6
  • Any reason not to use a common web framework like Flask or FastAPI? Commented Nov 28, 2021 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 ? Commented Nov 28, 2021 at 19:19
  • Try here: fastapi.tiangolo.com/advanced/websockets I've been using FastAPI for a while now with a lot of success. Commented Nov 28, 2021 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 ? Commented Nov 28, 2021 at 19:28
  • You launch the application with uvicorn. Just pass the appropriate flags. uvicorn.org/settings/#https Commented Nov 28, 2021 at 19:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.