what is the difference between socket.on and socket.broadcast.emit

Viewed 23

i was creating a chat application using nodejs and js in my nodejs file i have written these lines of code

const io = require('socket.io')(8000)
const users = {};
io.on('connection' , socket =>{
    socket.on('new-user-joined', name =>{              
        users[socket.id] = name ;
        socket.broadcast.emit('user-joined',name);      
    });

    socket.on('send',message =>{
        socket.broadcast.emit('receive',{message: message , name : users[socket.id]});
    });
});

so my question is what is the difference between socket.on and socket.broadcast.emit and also why we use socket.on and socket.broadcast.emit

1 Answers

socket.broadcast.emit will send the message to all the connected users.

socket.on will listener incoming data.

Example:

socket.on('new-user-joined', name =>{              
    users[socket.id] = name ;
    socket.broadcast.emit('user-joined',name);      
});

If anyone emits data to the new-user-joined channel this code structure will work.

socket.emit('new-user-joined', name);

You emit to the new-user-joined channel.

Related