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

标签 python ssl websocket

祝大家有美好的一天

我有一个用 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)

关于python - 在tornadoweb websockets服务器中实现SSL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20344206/

相关文章:

python - FK select 的显示选项 - Django Rest Framework

performance - 强制整个站点使用 HTTPS 的好习惯还是坏习惯?

java - "java.net.SocketTimeoutException: connect timed out"我的客户端无法调用网络服务

javascript - 在客户端和nodejs服务器上使用静态javascript文件

html - HTML WebSockets 是否为每个客户端维护一个开放的连接?这个规模吗?

mysql - 音隙外部存储

python - 即使在更改 header 和 IP 后,验证码也会使用请求。我是如何被跟踪的?

python - 如何在 Python GUI 的文本框中添加用户可调整大小的图像

java - Java 证书和 keystore 之间的关系

python - 如何在Python(brubeck)中解析表单发布的数据?