我正在使用Node.js ws
库来侦听第三方API上用户帐户中的事件。我为每个用户打开一个网络套接字,以监听该用户帐户中的事件。
结果是,第三方API并未为每个事件提供userID
,因此,如果我有10个Websocket连接到用户帐户,则无法确定事件来自哪个帐户。
在启动每个连接之前,我可以访问唯一的userId
。
是否可以将带有userId
标识符的websocket连接附加或包装到我建立的每个连接上,以便在接收到事件时可以访问自定义标识符,并随后知道哪个用户的帐户事件来自哪里?
下面的代码是真实代码和伪代码(即customSocket
)的组合
const ws = new WebSocket('wss://thirdparty-api.com/accounts', {
port: 8080,
});
ws.send(
JSON.stringify({
action: 'authenticate',
data: {
oauth_token: access_token,
},
})
);
// wrap and attach data here (pseudocode at top-level)
customSocket.add({userId,
ws.send(
JSON.stringify({
action: 'listen',
data: {
streams: ['action_updates'],
},
})
)
})
// listen for wrapper data here, pseudocode at top level
customSocket.emit((customData) {
ws.on('message', function incoming(data) {
console.log('incoming -> data', data.toString());
})
console.log('emit -> customData', customData);
})
看看socket.io
库,namespace
功能可以解决这个问题,但是我无法确定这是否正确。下面是他们的文档中的一个示例:
// your application has multiple tenants so you want to dynamically create one namespace per tenant
const workspaces = io.of(/^\/\w+$/);
workspaces.on('connection', socket => {
const workspace = socket.nsp;
workspace.emit('hello');
});
// this middleware will be assigned to each namespace
workspaces.use((socket, next) => {
// ensure the user has access to the workspace
next();
});
答案 0 :(得分:0)
我找到了一个非常简单的解决方案。首先创建一个消息处理函数:
const eventHandler = (uid, msg) => {
console.log(`${uid} did ${msg}`);
};
然后,当您为给定用户创建websocket时,将.on
事件与处理程序包装在一起:
const createSocketForUser = (uid, eventHandler) => {
const socket = new WebSocket(/* ... */);
socket.onmessage = (msg) => {
eventHandler(uid, msg)
};
return socket;
}