Websocket 连接错误:返回 101,但不升级 [英] Websocket connection error: returns 101, but does not upgrade
问题描述
我正在使用 ws 库设置一些 websocket.我正在努力使用握手设置授权.我已经向我们的服务器添加了一条路由以升级到 websocket 连接,如下所示:
I am setting up some websockets using ws library. I am struggling to set up authorisation using a handshake. I have added a route to our server to upgrade to a websocket connection like so:
.get(
'/chat',
authorisationFunction,
upgradeConnection,
),
websocket 服务器:
The websocket server:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 3030 });
这是upgradeConnection函数,如果授权成功就会运行:
This is the upgradeConnection function, which will run if authorisation is successful:
const upgradeConnection = (request, socket, head) => {
return wss.handleUpgrade(request, request.socket, head, function done(ws) {
return wss.emit('connection', ws, request);
});
}
我还有一个监听消息的功能:
I also have a function that listens to messages:
function webSocketsServer() {
wss.on('connection', (ws, request, client) => {
ws.on('message', message => {
ws.send(message);
});
});
}
一个连接被发出,我从我的服务器得到这个响应:
A connection gets emitted, and from my server I get this response:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: QyVvqadEcI1+ALka6j2pLKBkfNQ=
但随即在我的客户端上,我收到错误WebSocket 连接到 'ws://localhost:3000/chat' 失败:帧头无效".
but then immediately on my client I get the error "WebSocket connection to 'ws://localhost:3000/chat’ failed: Invalid frame header".
但是当我绕过握手并直接连接到我的 websocket 服务器时,我可以成功发送消息.错误仅发生在客户端,而不发生在后端.我错过了什么?
But when I bypass the handshake and connect directly to my websocket server, I can send messages successfully. The error is only on the client and not on the backend. What am I missing?
推荐答案
我不是 100% 确定这是唯一的方法,但可能会有所帮助,所以我发布了它.基于此答案,我会选择使用相同端口进行 http 和 websocket 连接的服务器.你可以这样实现:
I am not 100% sure it is the only way but might help so I post it. Based on this answer I would go for a server that uses the same port for http and websocket connections. You can achieve it like this:
const { createServer } = require('http')
const ws = require('ws')
const express = require('express')
const app = express()
const server = createServer(app)
app.get('/', (req, res) => {
res.send('I am a normal http server response')
})
const wsServer = new ws.Server({
server,
path: '/websocket-path',
})
wsServer.on('connection', (connection) => {
connection.send('I am a websocket response')
})
server.listen(3030, () => {
console.log(`Server is now running on http://localhost:3030`)
console.log(`Websocket is now running on ws://localhost:3030/<websocket-path>`)
})
因此,您的服务器会在端口 3030 上侦听正常的 http 请求.如果它在路径/websocket-path"上收到一个 websocket 连接请求,它就会被传递给 ws 连接处理程序,然后你就可以开始了.
So your server listens on port 3030 for normal http requests. If it gets a websocket connection request on path '/websocket-path' it is passed to the the ws connection handler and from there you are good to go.
这篇关于Websocket 连接错误:返回 101,但不升级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!