我有一个python websocket服务器和一个nodejs客户端,但我无法 来实现websocket's Protocol Handshake。
以下最小的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()
以下最小的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);
启动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-sockets
和gevent-websockets
论坛和问题
跟踪器),到目前为止没有任何运气。
我尝试了另一个简单的客户端websocat
。我这样调用它:
$ websocat ws://localhost:5001 --protocol aProtocol
我以交互方式提示了一些消息,并且它们被python服务器正确地回显了。
它之所以有效,是因为我认为websocat
(与nodejs的websocket
不同)
不要期望在与握手的过程中出现“ Sec-WebSocket-Protocol标头”
服务器。
但是我需要使用需要标题的nodejs客户端。
所以我的问题是:如何合并"Sec-WebSocket-Protocol"
python服务器握手响应中的标头?
答案 0 :(得分:1)
我知道这是一年多以前的事了,尽管您似乎已经快到了,但是看起来aProtocol
就需要替换为subprotocol
服务器期望。
或者作为替代,根据基础gevent-websocket中的flask-websockets uses完全省略:
// Subprotocol (2nd parameter) often is not required at all
var ws = new WebSocket('ws://localhost:5001/api');
对于未来的我或其他在这里绊倒的人,希望以下内容对您有所帮助。
在将浏览器连接到Node.JS apollo-server subscriptions的JavaScript中,我需要以下内容:
// 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-Protocol
标头被应用:
否则,如果未应用任何子协议,Sec-Websocket-Protocol
标头未发送且控制消息可见,我将看到Connection Closed: 1002
并且自然无法将消息发送到websocket: