With broadcasting in place, let's get into the final way we emit messages. We'll emit two events in socket.io, right when a user connects. Now, we'll not actually use broadcasting in this context, so we'll comment the broadcast object out and uncomment our old code. It should look like this:
socket.on('createMessage', (message) => {
console.log('createMessage', message);
io.emit('newMessage', {
from: message.from,
text: message.text,
createdAt: new Date().getTime()
});
// socket.broadcast.emit('newMessage', {
// from: message.from,
// text: message.text,
// createdAt: new Date().getTime()
//});
});
You'll first call socket.emit to emit a message to the user who joins. Your message should come from the admin, from Admin, and the text should say something like Welcome to the chat app.
Now, along with socket.emit, you'll also call socket.broadcast.emit, which will get sent to everybody but the user who joined, which means you can go ahead and set from equal to Admin once again, and you can set text equal to New user joined:
// socket.emit from Admin text Welcome to the chat app
// socket.broadcast.emit from Admin text New user joined
This means that when we join a chatroom, we'll see a message greeting us, and everyone else is going to see a message letting them know that someone else has joined. Both of these events are going to be newMessage events. We'll have to specify from (which is Admin), the text (which is whatever we said it should be), and createdAt.