Python 在Web websockets服务器中实现SSL

Python 在Web websockets服务器中实现SSL,python,ssl,websocket,Python,Ssl,Websocket,大家好 我有一个用python编写的websocket服务器,它为客户端提供对postgresql数据库表所做的更改。目前它使用标准的ws协议。我想实现SSL wss,但网站上似乎没有文档。感谢您的帮助 代码如下: import tornado.web import tornado.websocket import tornado.ioloop import tornado.httpserver import threading import select import psycopg2 i

大家好

我有一个用python编写的websocket服务器,它为客户端提供对postgresql数据库表所做的更改。目前它使用标准的ws协议。我想实现SSL wss,但网站上似乎没有文档。感谢您的帮助

代码如下:

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()
有什么建议吗

谢谢大家

试试这个:

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