Skip to main content
 首页 » 编程设计

python之在 tornadoweb websockets 服务器中实现 SSL

2025年05月04日29飞鱼

大家好,

我有一个用 python 编写的 websocket 服务器,它为客户端对 postgresql 数据库表所做的更改提供服务。目前它使用标准的 ws 协议(protocol)。我想实现 SSL wss,但 tornadoweb 站点上似乎没有文档。任何帮助表示赞赏!

代码如下:

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)