2017-10-04 69 views
0

我试图在使用HTML5 websocket和node.js创建的简单聊天中,在用户之间发送私人消息。如何在HTML5 websocket和node.js聊天中使用客户端ID?

当用户连接,我为他们创造(连接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 

有人可以请关于这个问题的建议?

任何帮助,将不胜感激。

在此先感谢。手动

+0

'CLIENTS = []'=>'CLIENTS = {}','CLIENTS.push(ws.id);'=>'CLIENTS [ws.id] = ws'。基本上,您保存了客户端ID,而不是客户端连接。 –

+0

这是什么意思:CLIENTS = [] => CLIENTS = {},CLIENTS.push(ws.id); =>客户端[ws.id] = ws? –

+0

用对象替换数组。保存整个ws连接,而不是id。 –

回答

1
  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} Specifies whether or not to track clients.

server.clients - A set that stores all connected clients. Please note that this property is only added when the clientTracking is truthy.

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是,所以你应该自己尝试。如果这真的是码头说的{Set},那么试试wss.clients.get(ID).send(data.message)

+0

不是'wss.clients [ID] .send(data.message);'应该是'wss.CLIENTS [ID] .send(data.message);'? –

+0

nope,尝试从示例代码 –

相关问题