如何在HTML5 WebSocket和Node.js Chat中使用客户端ID



我正在尝试在我使用html5 websocket和node.js创建的简单聊天中发送私人消息。

用户连接时,我为他们创建一个简单的ID(连接ID),然后将其添加到此CLIENTS=[];

当我进行console.log(CLIENTS);时,我会看到所有类似的ID:

[0, 1, 2]

现在,我需要使用ID向用户发送私人消息。

所以我继续进行此(出于测试目的,我只需要使用ID 2发送消息)

var express = require('express'),
        app = express(),
        http = require('http').Server(app),
        WebSocketServer = require('ws').Server,
        wss = new WebSocketServer({
            port: 8080
        });
    CLIENTS = [];
    connectionIDCounter = 0;

    app.use(express.static('public'));
    app.get('/', function(req, res) {
        res.sendFile(__dirname + '/index.html');
    });
    wss.broadcast = function broadcast(data) {
        wss.clients.forEach(function each(client) {
            client.send(data);
        });
    };
    wss.on('connection', function(ws) {
    /////////SEE THE IDs HERE////////////////
    ws.id = connectionIDCounter++;
    CLIENTS.push(ws.id);
    console.log(CLIENTS);

        ws.on('message', function(msg) {
            data = JSON.parse(msg);

    /////SEND A PRIVATE MESSAGE TO USER WITH THE ID 2//////
    CLIENTS['2'].send(data.message);
    });
});
http.listen(3000, function() {
    console.log('listening on *:3000');
});

运行代码时,我会收到以下错误:

TypeError: CLIENTS.2.send is not a function

有人可以就此问题提供建议吗?

任何帮助将不胜感激。

预先感谢。

  1. 手动跟踪客户端,替换: CLIENTS = []带有 CLIENTS = {}CLIENTS.push(ws.id);带有 CLIENTS[ws.id] = ws;

  2. 根据码头https://github.com/websockets/ws/blob/master/doc/ws.md应该是这样的:

new WebSocket.Server(options [,callback])
clientTracking {boolean}指定是否跟踪客户。

server.clients - 存储所有已连接客户端的集合。请注意 仅当 client tracking 是真实的。

时,才添加此属性
    var WebSocketServer = require('ws').Server,
        wss = new WebSocketServer({
                port: 8080,
                clientTracking: true
        });
    .....
    wss.on('connection', function(ws) {
       ws.on('message', function(msg) {
          data = JSON.parse(msg);
          wss.clients[ID].send(data.message);
       });
   });

我不知道哪种数据格式是wss.clients,因此您应该自己尝试。如Dock所说,如果这确实是{Set},请尝试wss.clients.get(ID).send(data.message)

最新更新