how to send message to specific client using ws node js

Solutions on MaxInterview for how to send message to specific client using ws node js by the best coders in the world

showing results for - "how to send message to specific client using ws node js"
Billie
04 Oct 2018
1var Server = require('ws').Server;
2var port = process.env.PORT || 9030;
3var ws = new Server({port: port});
4
5var sockets = [];
6ws.on('connection', function(w){
7  
8  var id = w.upgradeReq.headers['sec-websocket-key'];
9  console.log('New Connection id :: ', id);
10  w.send(id);
11  w.on('message', function(msg){
12    var id = w.upgradeReq.headers['sec-websocket-key'];
13    var message = JSON.parse(msg);
14    
15    sockets[message.to].send(message.message);
16
17    console.log('Message on :: ', id);
18    console.log('On message :: ', msg);
19  });
20  
21  w.on('close', function() {
22    var id = w.upgradeReq.headers['sec-websocket-key'];
23    console.log('Closing :: ', id);
24  });
25
26  sockets[id] = w;
27});
28
29