Fabrizio Mazzoni
Fabrizio Mazzoni

Reputation: 1909

Implement SSL in tornadoweb websockets server

Good Day to all,

I have a websocket server written in python that serves clients changes done to a postgresql database table. Presently it uses the standard ws protocol. I would Like to implement SSL wss but there seems to be no documentation on the tornadoweb site. Any help appreciated!

Code as follows:

import tornado.web
import tornado.websocket
import tornado.ioloop
import tornado.httpserver
import threading


import select
import psycopg2
import psycopg2.extensions

# This is a global variable to store all connected clients
websockets = []

# Connect to DB to listen for notifications
conn = psycopg2.connect("host=xxx.xxx.xxx.xxx dbname=mydb user=xxx port=yyy")
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)

curs = conn.cursor()
curs.execute("LISTEN notifier;")

# Create the websocket 
class WebSocketHandler(tornado.websocket.WebSocketHandler):
    @tornado.web.asynchronous
    # Add to global variable the connected client
    def open(self):
    self.set_nodelay(True)

    # on disconnect remove client
        def on_close(self):
        # Search for it in the list. If it matches with us (the client) then remove it as he has quit the con
        try:
        for websocket in websockets:
            if websocket[0] == self:
                websockets.remove(websocket)
    except ValueError:
        print ValueError

def on_message(self, message):
    if self not in websockets:
        websockets.append([self,message])

def on_pong(self, data):
    print data

# This is the function that polls the database for changes, then it sends change to clients through websockets
def db_listener():  
while 1:
    if select.select([conn],[],[],5) == ([],[],[]):
        for websocket in websockets:
            # ping the client regularly to avoid disconnect
            websocket[0].ping("ping")
    else:
        conn.poll()
        while conn.notifies:
            notify = conn.notifies.pop()
            details = notify.payload.split(",")
            if len(details) > 1:
                for websocket in websockets:
                    if details[34] in websocket[1]:
                            websocket[0].write_message(notify.payload)

application = tornado.web.Application([
    (r"/websocket", WebSocketHandler),
])

if __name__ == "__main__":
# Start a separate thread for every client so that we do not block the main websockets program!
    threading.Thread(target=db_listener).start()
    application.listen(5252)
    tornado.ioloop.IOLoop.instance().start()

Any suggestions?

Thanks to all!!

Upvotes: 2

Views: 1412

Answers (1)

Praveen
Praveen

Reputation: 2419

try this:

server = tornado.httpserver.HTTPServer(application, ssl_options = {
        "certfile": "path-to-crt-file",
        "keyfile": "path-to-key-file",
    })
server.listen(5252)

Upvotes: 2

Related Questions