Answers for "how to send message to specific client using ws node js"

0

how to send message to specific client using ws node js

var Server = require('ws').Server;
var port = process.env.PORT || 9030;
var ws = new Server({port: port});

var sockets = [];
ws.on('connection', function(w){
  
  var id = w.upgradeReq.headers['sec-websocket-key'];
  console.log('New Connection id :: ', id);
  w.send(id);
  w.on('message', function(msg){
    var id = w.upgradeReq.headers['sec-websocket-key'];
    var message = JSON.parse(msg);
    
    sockets[message.to].send(message.message);

    console.log('Message on :: ', id);
    console.log('On message :: ', msg);
  });
  
  w.on('close', function() {
    var id = w.upgradeReq.headers['sec-websocket-key'];
    console.log('Closing :: ', id);
  });

  sockets[id] = w;
});
Posted by: Guest on July-05-2020

Code answers related to "how to send message to specific client using ws node js"

Code answers related to "Javascript"

Browse Popular Code Answers by Language