nodejs socketio emit code example
Example 1: js socket.emit
const socket = io('ws://localhost:3000');
socket.on('connect', () => {
// either with send()
socket.send('Hello!');
// or with emit() and custom event names
socket.emit('salutations', 'Hello!', { 'mr': 'john' }, Uint8Array.from([1, 2, 3, 4]));});
// handle the event sent with socket.send()
socket.on('message', data => {
console.log(data);
});
// handle the event sent with socket.emit()
socket.on('greetings', (elem1, elem2, elem3) => {
console.log(elem1, elem2, elem3);
});
Example 2: socket emit to specific room using nodejs socket.io
io.on('connection', socket => { socket.on('disconnecting', () => { const rooms = Object.keys(socket.rooms); // the rooms array contains at least the socket ID }); socket.on('disconnect', () => { // socket.rooms === {} });});
Example 3: socket emit to specific room using nodejs socket.io
io.on('connection', socket => { socket.on('say to someone', (id, msg) => { socket.to(id).emit('my message', msg); });});