Directing Socket.IO messages

Now that we have access to usernames, we can also announce the arrival of users in the lobby. We can do this by extending our Socket.IO connection event handler as given here src/realtime/chat.js:

'use strict';

module.exports = io => {

    io.on('connection', (socket) => {
        const username = socket.request.user.name;

        if(username) {
            socket.broadcast.emit('chatMessage', {
                username: username,
                message: 'has arrived',
                type: 'action'
            });
        }

        socket.on('chatMessage', (message) => {
            io.emit('chatMessage', {
                username: username,
                message: message
            });
        });
    });
 }

Here, we use socket.broadcast.emit, rather than io.emit, to send the event to all clients except for the current socket. Note that we also add extra data to the message. ...

Get Learning Node.js for .NET Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.