websocket server send message to client code example
Example: 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;
});