Step 3: To notify clients when a new chat message is
sent, use a WebSocket, which allows for bidirectional communication
between clients and a server. Download a package called socket.io. To
use the package in your code, go to index.js, and add the following
near the top:
let socketio = require(`socket.io`)
At the bottom, replace app.listen with:
let server = app.listen(3000)
let io = new socketio.Server(server)
The
io
object can be used to broadcast data to all
clients. To broadcast a new chat message, add the following at the
start of your endpoint for posting chat messages:
io.emit(`message`, request.body.message)
You will have clients listen for broadcasted chat messages in the
next step.