Hey guys just started using ws how would I only send or broadcast a message from a client to all other clients except the sender. Theres very little example code I couldn't find anything.
//when the client sends a message
ws.on("message", function(message) {
console.log("Received: %s", message);
server.broadcast(message);
my broadcast method has a for each loop currently
server.clients.forEach(function(client) {
client.send(data);
}
You seem to be doing it correctly. Though, Socket.io already enhances this
WebSocket implementation with additional support for broadcasting.
On Mar 7, 2015 3:51 AM, "cra0kalo" [email protected] wrote:
Hey guys just started using ws how would I only send or broadcast a
message from a client to all other clients except the sender. Theres very
little example code I couldn't find anything.//when the client sends a message ws.on("message", function(message) { console.log("Received: %s", message); server.broadcast(message);my broadcast method has a for each loop currently
server.clients.forEach(function(client) { client.send(data); }—
Reply to this email directly or view it on GitHub
https://github.com/websockets/ws/issues/465.
@glennschler are you seriously advising socket.io because there a single if statement missing in the forEach code? I don't even..
ws.on("message", function(message) {
server.clients.forEach(function(client) {
if (client !== ws) client.send(data);
});
});
@cra0kalo The only thing that your code was missing was a simple if statement to check if the client that you received from the forEach was not the same as the ws client that received the message.
Thankyou 3rd-Eden got it working sir
console.log("Broadcasting: " + data + " to " + server.clients.length + " clients.");
server.clients.forEach(function(client)
{
if (sender == client) //don't send it to the sender that wouldn't make sense
return;
client.send(data);
});
Most helpful comment
@glennschler are you seriously advising socket.io because there a single if statement missing in the
forEachcode? I don't even..@cra0kalo The only thing that your code was missing was a simple
ifstatement to check if the client that you received from the forEach was not the same as thewsclient that received the message.