SocketIO Emit cheatsheet

September 27, 2023

SocketIO

SocketIO Emit cheatsheet

Thuta Sann

Thuta Sann

SocketIO Emit cheatsheet between server and client


Share This Snippet To :

This is my first snippet about SocketIO. I just wanna share this useful cheatsheet from socket.io documentation here.

Ref : https://socket.io/docs/v4/emit-cheatsheet/

// ----------- Server side io.on("connection", (socket) => { // basic emit back to sender socket.emit(/* ... */); // to all clients in the current namespace except the sender socket.broadcast.emit(/* ... */); // to all clients in room1 except the sender socket.to("room1").emit(/* ... */); // to all clients in room1 and/or room2 except the sender socket.to(["room1", "room2"]).emit(/* ... */); // to all clients in room1 io.in("room1").emit(/* ... */); // to all clients in room1 and/or room2 except those in room3 io.to(["room1", "room2"]).except("room3").emit(/* ... */); // to all clients in namespace "myNamespace" io.of("myNamespace").emit(/* ... */); // to all clients in room1 in namespace "myNamespace" io.of("myNamespace").to("room1").emit(/* ... */); // to individual socketid (private message) io.to(socketId).emit(/* ... */); // to all clients on this node (when using multiple nodes) io.local.emit(/* ... */); // to all connected clients io.emit(/* ... */); // to all clients, with one acknowledgement per client io.timeout(5000).emit("hello", "world", (err, responses) => { if (err) { // some clients did not acknowledge the event in the given delay } else { console.log(responses); // one response per client } }); // WARNING: `socket.to(socket.id).emit()` will NOT work, as it will send to everyone in the room // named `socket.id` but the sender. Please use the classic `socket.emit()` instead. // with acknowledgement socket.emit("question", (answer) => { // ... }); // without compression socket.compress(false).emit(/* ... */); // a message that might be dropped if the low-level transport is not writable socket.volatile.emit(/* ... */); // with timeout socket.timeout(5000).emit("my-event", (err) => { if (err) { // the other side did not acknowledge the event in the given delay } }); }); // ----------- Client side // basic emit socket.emit(/* ... */); // with acknowledgement socket.emit("question", (answer) => { // ... }); // without compression socket.compress(false).emit(/* ... */); // a message that might be dropped if the low-level transport is not writable socket.volatile.emit(/* ... */); // with timeout socket.timeout(5000).emit("my-event", (err) => { if (err) { // the other side did not acknowledge the event in the given delay } });

Cookie

I baked some cookies that you have to accept, if you want to enjoy my portfolio.
In order to gather information and make improvements, I should use some third-party cookies too, Can I?