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. This time we add a type
field (set to 'action'
for the arrival message...