如何在python websocket服务器握手响应中设置“ Sec-WebSocket-Protocol”标头?

问题描述 投票:3回答:1

我有一个python websocket服务器和一个nodejs客户端,但我无法实现websocket's Protocol Handshake

python服务器代码

以下最小的Websocket服务器利用了Flask-sockets(使用gevent-websocket)。文件名是ws_server.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-
from flask import Flask, request, Response
from flask_sockets import Sockets

app = Flask(__name__)
sockets = Sockets(app)

@sockets.route('/')
def echo_socket(ws):
    # print("type request: ",type(request))
    # print("dir  request: ", dir(request))
    print("request.headers: ", request.headers)
    # print("type ws: ",type(ws))
    # print("dir  ws: ",dir(ws))

    if hasattr(request, "Sec-Websocket-Protocol"):
        print(request.headers["Sec-Websocket-Protocol"])
    else:
        print("INFO: No protocol specified")

    if request.headers["Sec-Websocket-Protocol"] == "aProtocol":
        print("INFO: protocol is OK")
    else:
        print("INFO: protocol not accepted: closing connection")
        ws.close()

    while not ws.closed:
        message = ws.receive()
        if message:
            print("received: "+message)
            ws.send(message)

    if ws.closed:
        print("INFO: connection has been closed")

if __name__ == "__main__":
    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler
    server = pywsgi.WSGIServer(('', 5001), app, handler_class=WebSocketHandler)
    server.serve_forever()

nodejs客户端代码

以下最小的Websocket客户端利用了websocket图书馆。文件名是app.js

'use strict'

var WebSocketClient = require('websocket').client;
var client = new WebSocketClient();

function connectToServer(uri,protocol){
    client.on('connectFailed', function (error) {
        console.log('Connect Error: ' + error.toString());
    });

    client.on('connect', function (connection) {
        console.log('WebSocket Client Connected');

        connection.on('error', function (error) {
            console.log("Connection Error: " + error.toString());
        });

        connection.on('close', function () {
            console.log('echo-protocol Connection Closed');
        });

        connection.on('ping', () => {
            connection.pong();
        });

        connection.on('message', function (message) {
            if (message.type === 'utf8') {
                console.log("Received message is: '" + message.utf8Data + "'");
            }
        });
        console.log("sending SOMETHING");
        connection.sendUTF("SOMETHING");
    });
    client.connect(uri, protocol);
}

const wsHostAndPort = process.env.WSHSTPRT || "ws://echo.websocket.org:80";
const wsProtocol = process.env.WSPRTCL || []; // [] for no protocol

console.log("connecting to: ",wsHostAndPort,"with protocol",wsProtocol);
connectToServer(wsHostAndPort,wsProtocol);

来自作为客户端的nodejs的连接

启动python ws服务器:

$ python3 ws_server.py

从nodejs与客户端连接:

$ WSHSTPRT=ws://localhost:5001/ WSPRTCL="aProtocol" node app.js

客户端的输出是

connecting to:  ws://localhost:5001/ with protocol aProtocol
Connect Error: Error: Expected a Sec-WebSocket-Protocol header.

服务器终端的输出是:

request.headers:  Upgrade: websocket
Connection: Upgrade
Sec-Websocket-Version: 13
Sec-Websocket-Key: +QjH5xejDI+OQZQ0OZcWEQ==
Host: localhost:5001
Sec-Websocket-Protocol: aProtocol


INFO: No protocol specified
INFO: protocol is OK
INFO: connection has been closed

在我看来,python服务器需要设置一个标题为"Sec-WebSocket-Protocol"具有与从客户。但是我不知道该怎么做。我搜索了互联网(主要是flask-socketsgevent-websockets论坛和问题追踪器),到目前为止没有任何运气。

我尝试了另一个简单的客户端websocat。我这样调用它:$ websocat ws://localhost:5001 --protocol aProtocol我以交互方式提示了一些消息,并且它们被python服务器正确地回显了。之所以有效,是因为我认为websocat(与nodejs的websocket不同)不要期望在与握手的过程中出现“ Sec-WebSocket-Protocol标头”服务器。

但是我需要使用需要标题的nodejs客户端。所以我的问题是:如何合并"Sec-WebSocket-Protocol"python服务器握手响应中的标头?

python node.js websocket handshake
1个回答
0
投票

我知道这是一年前的事,尽管您似乎已经快到了,但看起来好像已经前进了,只需要用服务器期望的aProtocol替换subprotocol

或者,根据subprotocol的基础gevent-websocket完全省略:

flask-websockets uses

为了将来我或其他在这里跌跌撞撞的人,我希望以下内容能有所帮助。

在将浏览器连接到Node.JS // Subprotocol (2nd parameter) often is not required at all var ws = new WebSocket("ws://localhost:8000/api"); 的JavaScript中,我需要以下内容:

apollo-server subscriptions

然后我会看到// Pasted into Firefox console const token = '...'; // A bearer token, if auth is needed const subprotocol = 'graphql-ws'; w = new WebSocket('ws://localhost:5000/graphql', subprotocol); w.send(JSON.stringify({"type":"connection_init","payload":{"authToken":token}})); 标头被应用:Sec-Websocket-ProtocolSec-Websocket-Protocol header

否则,如果未应用任何子协议,Message sent and ack received标头未发送且控制消息可见,我会看到Sec-Websocket-Protocol,自然无法将消息发送到Websocket:

Connection Closed: 1002

© www.soinside.com 2019 - 2024. All rights reserved.