To get started, we'll update the createMessage listener. Currently, all we do is log the data to the screen. But here, instead of just logging it, we actually want to emit a new event, a newMessage event, to everybody, so each connected user gets the message that was sent from a specific user. In order to get that done, we'll call a method on io, which will be io.emit:
socket.on('createMessage', (message) => {
console.log('createMessage', message);
io.emit
});
Socket.emit emits an event to a single connection, whereas io.emit emits an event to every single connection. Here, we are going to emit the newMessage event, specifying it as our first argument. The second argument, as with socket.emit, is the data you want to send:
socket.on('createMessage', (message) => {
console.log('createMessage', message);
io.emit('newMessage', {
})
});
Now, we know we'll get a from property and a text property from the client—those appear in socket.emit for the createMessage event in index.js—which means what we need to do is pass those along, setting from equal to message.from, and setting text equal to message.text:
io.emit('newMessage', {
from: message.from,
text: message.text
})
Now, along with from and text, we'll also specify a createdAt property, which will be generated by the server to prevent a specific client from spoofing the time a message was created. The createdAt property is set equal to new Date, and we'll call the getTime method to get that timestamp back, which we've done before:
io.emit('newMessage', {
from: message.from,
text: message.text,
createdAt: new Date().getTime()
});
Now that we have this in place, we actually have messaging wired up. We can go ahead and remove our emit calls—the newMessage emit call and the createMessage emit call—from server.js and index.js, respectively, making sure to save both files. With this in place, we can go ahead and test this by opening up two connections to the server and emitting some events.