【发布时间】:2020-08-19 07:57:37
【问题描述】:
在客户端应用程序成功建立与 Node 服务器(例如,Electron 应用程序)的连接之前提供一些检查的最佳方法是什么。
来自 websocket/ws 库的Ipinca 建议使用 server.on('upgrade', ...) 事件监听器,但是使用它,我们只能检查当前从客户端发送的数据。
const http = require('http');
const WebSocket = require('ws');
const server = http.createServer();
const wss = new WebSocket.Server({ noServer: true });
wss.on('connection', function connection(ws, request, ...args) {
// ...
});
server.on('upgrade', async function upgrade(request, socket, head) {
// Do what you normally do in `verifyClient()` here and then use
// `WebSocketServer.prototype.handleUpgrade()`.
let args;
try {
args = await getDataAsync();
} catch (e) {
socket.destroy();
return;
}
wss.handleUpgrade(request, socket, head, function done(ws) {
wss.emit('connection', ws, request, ...args);
});
});
server.listen(8080);
但是,如果我们想检查用户是否已经通过身份验证,并且在这种情况下,我们不想再次对他进行身份验证,该怎么办?在为这些检查打开 WebSocket 连接之前,我们是否需要发送一些 http 请求,对于 Ws 和 Http 协议使用相同的端口是一种好习惯吗?
谢谢!
【问题讨论】:
标签: node.js http vue.js websocket electron