WebSocket连接到自签名服务器

时间:2014-10-31 22:17:09

标签: python ssl https websocket tornado

我想连接到我的websocket服务器,我基本上需要通过https。

from tornado.options import define, options
from imaplib import Commands
define("port", default=443, help="run on the given port", type=int)

class WebSocketHandler(tornado.websocket.WebSocketHandler):
def __init__(self, *args, **kwargs):
    super(WebSocketHandler, self).__init__(*args, **kwargs);
    pass;
def open(self):
    print 'new connection'
    self.write_message("connected")

def on_message(self, message):
    print 'message received %s' % message
    self.write_message('message received %s' % message)

def on_close(self):
    print 'connection closed'

def check_origin(self, origin):
    return True;

if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(
       handlers=[
           (r"/ws", WebSocketHandler)
       ]
    )
    data_dir = "/home/pi/projects/WebSocketOverHttps/";
    httpServer = tornado.httpserver.HTTPServer(app, ssl_options = {
       "certfile": os.path.join(data_dir, "cert.crt"),
       "keyfile": os.path.join(data_dir, "key.key"),
    });
    httpServer.listen(options.port)
    print "Listening on port:", options.port
    tornado.ioloop.IOLoop.instance().start()

问题是我的浏览器说:“WebSocket连接到'wss://192.168.1.8/ws'失败:WebSocket打开握手被取消了”

我试图做的事情是: 1)双击cert文件,将证书添加到系统(win 8.1 PRO x64) 2)在同一系统上添加证书到谷歌浏览器(通过浏览器的设置)

当我重新实现它以使用http而不是https时,我能够连接到此服务器,因此与机器的物理连接看起来没问题。

我的证书是自签名的,由命令生成:

sudo openssl req -x509 -nodes -days 365000 -newkey rsa:2048 -keyout /etc/apache2/ssl/apache.key -out /etc/apache2/ssl/apache.crt

这就是我尝试连接它的方式:

var socket = new WebSocket("wss://192.168.1.8:443/ws");

1 个答案:

答案 0 :(得分:2)

正如@BenDarnell发布的那样,我们必须通过浏览到此服务器的页面来接受此证书。然后您的浏览器将通知此站点不受信任。让您的浏览器使用此不受信任的证书以及所有这些证书。以下是您需要在代码中放置的代码:

class MainHandler(tornado.web.RequestHandler):
  def get(self):
    loader = tornado.template.Loader(".")
    self.write(loader.load("index.html").generate());

app = tornado.web.Application(
handlers=[
   (r"/ws", WebSocketHandler),
   (r"/", MainHandler)
])

data_dir = "/home/pi/projects/Something";
ssl_options_dict = {
    "certfile": os.path.join(data_dir, "cert.crt"),
    "keyfile": os.path.join(data_dir, "key.key"),
};

httpServer = tornado.httpserver.HTTPServer(app, ssl_options = ssl_options_dict);