David Hope
David Hope

Reputation: 1536

How to use the client ID in HTML5 websocket and node.js chat?

I'm trying to send private message between users in a simple chat that I created using HTML5 websocket and node.js.

When the users connect, I create a simple ID for them (connection ID) and add that to this CLIENTS=[];

When I do a console.log(CLIENTS);, I see all the IDs like this:

[0, 1, 2]

Now I need to use the IDs to send Private messages to the users.

So i went ahead and this (For the testing purposes, I just need to send the message to the user with 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');
});

When I run my code, I get the following error:

TypeError: CLIENTS.2.send is not a function

Could someone please advice on this issue?

Any help would be appreciated.

Thanks in advance.

Upvotes: 0

Views: 6617

Answers (1)

Nazar Sakharenko
Nazar Sakharenko

Reputation: 1007

  1. Track clients manually, replace: CLIENTS = [] with CLIENTS = {}, and CLIENTS.push(ws.id); with CLIENTS[ws.id] = ws;

  2. According to docks https://github.com/websockets/ws/blob/master/doc/ws.md should be something like this:

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);
       });
   });

I don't know what data format wss.clients is, so you should try it by yourself. If this is really {Set} as docks said, then try wss.clients.get(ID).send(data.message)

Upvotes: 3

Related Questions