Skip to content

Instantly share code, notes, and snippets.

@johannesMatevosyan
Last active May 8, 2023 10:08
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save johannesMatevosyan/5ec0f7139c1804cc3bbb to your computer and use it in GitHub Desktop.
Save johannesMatevosyan/5ec0f7139c1804cc3bbb to your computer and use it in GitHub Desktop.
Websockets: send message to all clients except sender.
var http = require('http');
var Static = require('node-static');
var WebSocketServer = new require('ws');
// list of users
var CLIENTS=[];
var id;
// web server is using 8081 port
var webSocketServer = new WebSocketServer.Server({ port: 8081 });
// check if connection is established
webSocketServer.on('connection', function(ws) {
id = Math.random();
console.log('connection is established : ' + id);
CLIENTS[id] = ws;
CLIENTS.push(ws);
ws.on('message', function(message) {
console.log('received: %s', message);
var received = JSON.parse(message);
if(received.type == "login"){
ws.send(message); // send message to itself
sendNotes(JSON.stringify({
user: received.name,
type: "notes"
}), ws, id);
}else if(received.type == "message"){
sendAll(message); // broadcast messages to everyone including sender
}
});
ws.on('close', function() {
console.log('user ' + id + ' left chat');
delete CLIENTS[id];
});
});
function sendNotes(message, ws, id) {
console.log('sendNotes : ', id);
if (CLIENTS[id] !== ws) {
console.log('IF : ', message);
for (var i = 0; i < CLIENTS.length; i++) {
CLIENTS[i].send(message);
}
}else{
console.log('ELSE : ', message);
}
}
function sendAll(message) {
console.log('sendAll : ');
for (var j=0; j < CLIENTS.length; j++) {
// Отправить сообщения всем, включая отправителя
console.log('FOR : ', message);
CLIENTS[j].send(message);
}
}
function customFilter(ws){
if(ws.hasOwnProperty('id')){
for(var i=0; i<ws.keys(id).length; i++){
console.log(id);
}
}
}
var fileServer = new Static.Server('.');
http.createServer(function (req, res) {
fileServer.server(req, res);
}).listen(8080, function(){
console.log("Server is listening 8080 port.");
});
console.log("Server is running on 8080 and 8081 ports");
@muxahuk
Copy link

muxahuk commented Mar 14, 2016

You'r calling sendNotes wrong. You'll always will be CLIENTS[id] !== ws => false.
You need to modify sendAll function or write sendNotes like sendAll except inside a loop you should check the id with passed to function id...

function sendAllExcept( message, ids ) {
    if( undefined === ids ) throw new Error( 'ids must be specified' );
    if( ! Array.isArray(ids) ) ids = [ ids ];
    for( var i = 0, cLength = CLIENTS.length; i < cLength; i++) {
        if( ids.indexOf( i ) !== -1 ) continue; /// or some othere check if shouldnt send to these client do continue
        CLIENTS[i].send( message );
    }
}

something like that

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment