如何向 ws 库中的特定用户发送消息?

air*_*eak 8 websocket node.js socket.io

我正在探索不同的 websocket 库进行自学,我发现这个库真的很棒ws-node。我正在 ws-node 库中构建基本的一对一聊天

我的问题是ws 中的socket.io函数等价于什么?socket.to().emit()因为我想向特定用户发送消息。

前端 - socket.io

socket.emit("message", { message: "my name is dragon", userID: "123"});
Run Code Online (Sandbox Code Playgroud)

服务器端-socket.io

// listening on Message sent by users
socket.on("message", (data) => {
    // Send to a specific user for 1 on 1 chat
    socket.to(data.userID).emit(data.message);
});
Run Code Online (Sandbox Code Playgroud)

WS-- 后端

const express = require('express');
const http =  require('http');
const WebSocket = require('ws');
const express = require('express');
const http =  require('http');
const WebSocket = require('ws');

const app = express();

const server = http.createServer(app);

const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {

    ws.on('message', (data) => {   
        \\ I can't give it a extra parameter so that I can listen on the client side, and how do I send to a specific user?
        ws.send(`Hello, you sent -> ${data.message}`);
    });
});
Run Code Online (Sandbox Code Playgroud)

Mar*_*nde 2

没有等效的方法。socket.io配备了很多帮助者和功能,这将使您的生活更轻松,例如房间、活动......

socket.io是一个实时应用框架,而ws只是一个WebSocket客户端。


您需要制作自定义包装器:

const sockets = {};

function to(user, data) {

    if(sockets[user] && sockets[user].readyState === WebSocket.OPEN)
        sockets[user].send(data);
}

wss.on('connection', (ws) => {

    const userId = getUserIdSomehow(ws);
    sockets[userId] = ws;

    ws.on('message', function incoming(message) {
        // Or get user in here
    });

    ws.on('close', function incoming(message) {
        delete sockets[userId];
    });

});
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

to('userId', 'some data');
Run Code Online (Sandbox Code Playgroud)

在我看来,如果您寻求该功能,您应该使用socket.io. 它很容易集成,有很多支持,并且有多种语言的客户端库。

如果您的前端使用,socket.io您也必须在服务器上使用它。