Create websocket over ssl and https server in python

932 Views Asked by At

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 ?

1

There are 1 best solutions below

0
Dhiraj Dhule On

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.