我正在尝试在node js中创建客户端WebSocket。WebSocket服务器在浏览器(firefox)中运行。代码和错误信息如下。它在浏览器中工作时在Nodejs中不工作。这是什么原因呢?我该如何解决?
编码(Node JS):
const WebSocket = require('ws');
const { randomBytes } = require('crypto');
const headers = {
Accept: '*/*',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'q=0.8,en-US',
'Cache-Control': 'no-cache',
Connection: 'keep-alive, Upgrade',
cookie: 'key=UE2BQmTF;',
Pragma: 'no-cache',
'Sec-WebSocket-Extensions': 'permessage-deflate',
'sec-websocket-key': randomBytes(16).toString('base64'),
'Sec-WebSocket-Version': '13',
Upgrade: 'websocket',
'User-Agent':
'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0',
};
ws = new WebSocket(wurl, { headers });
ws.binaryType = 'arraybuffer';
ws.on('open', () => {
console.log('connected', Date());
});
ws.on('close', () => {
console.log('disconnected', Date());
});
错误:
Error: Invalid Sec-WebSocket-Accept header
2020-01-25T14:51:57.930773+00:00 app[web.1]: at ClientRequest.<anonymous> (/app/node_modules/ws/lib/websocket.js:603:7)
2020-01-25T14:51:57.930775+00:00 app[web.1]: at ClientRequest.emit (events.js:223:5)
2020-01-25T14:51:57.930778+00:00 app[web.1]: at TLSSocket.socketOnData (_http_client.js:490:11)
2020-01-25T14:51:57.930780+00:00 app[web.1]: at TLSSocket.emit (events.js:223:5)
2020-01-25T14:51:57.930782+00:00 app[web.1]: at addChunk (_stream_readable.js:309:12)
2020-01-25T14:51:57.930785+00:00 app[web.1]: at readableAddChunk (_stream_readable.js:290:11)
2020-01-25T14:51:57.930787+00:00 app[web.1]: at TLSSocket.Readable.push (_stream_readable.js:224:10)
2020-01-25T14:51:57.930789+00:00 app[web.1]: at TLSWrap.onStreamRead (internal/stream_base_commons.js:181:23)
2020-01-25T14:51:57.930791+00:00 app[web.1]: Emitted 'error' event on WebSocket instance at:
2020-01-25T14:51:57.930793+00:00 app[web.1]: at Object.onceWrapper (events.js:313:26)
2020-01-25T14:51:57.930795+00:00 app[web.1]: at TLSSocket.emit (events.js:223:5)
2020-01-25T14:51:57.930797+00:00 app[web.1]: at emitErrorNT (internal/streams/destroy.js:92:8)
2020-01-25T14:51:57.930799+00:00 app[web.1]: at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
2020-01-25T14:51:57.930801+00:00 app[web.1]: at processTicksAndRejections (internal/process/task_queues.js:81:21)
1条答案
按热度按时间brvekthn1#
'sec-websocket-key'由ws sec-websocket-key自动生成