将javascript安全websocket客户端连接到python websocket asyncio服务器

时间:2017-05-17 07:39:35

标签: javascript python websocket python-asyncio

我在javascript websocket客户端和python服务器(使用asyncio和websocket模块)之间建立连接时遇到了麻烦。当我使用简单的websocket(不安全)时,连接工作正常,但是当我试图使用安全websocket(wss)时,我收到错误:

   WebSocket connection to 'wss://127.0.0.1:6169/' failed: Error in connection 
   establishment: net::ERR_SSL_PROTOCOL_ERROR

我的服务器代码:

async def app(websocket, path):
    while True :
        data = await websocket.recv()
        if (data== "close"):
            print("connection with client closed.")
            break
        data = data.encode()
        arr = data.split("~".encode())
        for i in range(0,4):
            arr[i]=arr[i].decode()
        resualt=algo(arr)
        await websocket.send(resualt)

server = websockets.serve(app, '0.0.0.0', 6169)

asyncio.get_event_loop().run_until_complete(server)
asyncio.get_event_loop().run_forever()

我的客户代码:

var st=password+"~"+url+"~"+clientid+"~"+option;
                    if ('WebSocket' in window){
                        var socket = new WebSocket("wss://127.0.0.1:6169/");
                        socket.onopen = function (evt) {
                            socket.send(st);
                        };
                        socket.onmessage = function (evt) {
                            alert("scrool extension page down to see the password");
                            $('#res').val(evt.data);
                            socket.send("close");
                        };
                        socket.onerror = function (evt) {
                            alert("the error is: "+evt.data);
                        };
                    }
                    else {
                       alert("web socket is not supported")
                    }

当我替换这一行时:

    var socket = new WebSocket("wss://127.0.0.1:6169/");

这一个:

    var socket = new WebSocket("ws://127.0.0.1:6169/");

everthing工作正常。

如果有人知道我的错误是什么,或者如何在带有websocket库的js客户端和带有asyncio和web套接字模块的python服务器之间成功建立安全连接,请帮忙。我在网上搜索了一个有效的例子,但我找不到。

我还尝试通过将代码更改为:

来在我的服务器中启用TLS
    context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) 
    context.load_default_certs(purpose=ssl.Purpose.CLIENT_AUTH) 
    server = websockets.serve(app, '0.0.0.0', 6169, ssl=context) 

但它仍然无法正常工作并给我以下错误:

    WebSocket connection to 'wss://127.0.0.1:6169/' failed: Error in 
    connection establishment: net::ERR_CONNECTION_CLOSED –

0 个答案:

没有答案