Build a Socket.IO server that will notify all the connected clients to the "commonRoom" room when a new socket is connected.
- Create a new file named rooms-server.js
- Include the Socket.IO NPM module and initialize a new HTTP server:
const http = require('http') const fs = require('fs') const path = require('path') const io = require('socket.io')() const app = http.createServer((req, res) => { if (req.url === '/') { fs.readFile( path.resolve(__dirname, 'rooms-client.html'), (err, data) => { if (err) { res.writeHead(500) return void res.end() } res.writeHead(200) res.end(data) } ) } else { res.writeHead(403) res.end() } })
- Specify the path where new connections will be made:
io.path('/socket.io')
- Use the root namespace to listen for events:
const root = io.of('/')
- Define a method that will be used to emit an updateClientCount event to all socket clients connected to the "commonRoom" providing as an argument the number of connected clients:
const notifyClients = () => { root.clients((error, clients) => { if (error) throw error root.to('commonRoom').emit( 'updateClientCount', clients.length, ) }) }
- On connection, all newly connected Socket clients will join the commonRoom. Then, the server will emit a welcome event. After this, notify all connected sockets to update the number of connected clients and also do the same operation once a client is disconnected:
root.on('connection', socket => { socket.join('commonRoom') socket.emit('welcome', `Welcome client: ${socket.id}`) socket.on('disconnect', notifyClients) notifyClients() })
- Listen on port 1337 for new connections and attach Socket.IO to the HTTP server:
io.attach(app.listen(1337, () => { console.log( 'HTTP Server and Socket.IO running on port 1337' ) }))
- Save the file.
After this, build a Socket.IO client that will connect to the Socket.IO server and populate the HTML content with received data:
- Create a new file named rooms-client.html
- Add the following code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Socket.IO Client</title> </head> <body> <h1 id="title"> Connected clients: <span id="n"></span> </h1> <p id="welcome"></p> <script src="http://localhost:1337/socket.io/socket.io.js">
</script> <script
src="https://unpkg.com/@babel/standalone/babel.min.js">
</script> <script type="text/babel"> // Code here </script> </body> </html>
- Inside the script tag, add code in the following steps, starting from step 4
- Define two constants that will make a reference to two HTML elements that we will update according to the data sent by the Socket.IO Server:
const welcome = document.getElementById('welcome') const n = document.getElementById('n')
- Define a Socket.IO Client Manager:
const manager = new io.Manager( 'http://localhost:1337', { path: '/socket.io' }, )
- Use the root namespace which is the one used in the Socket.IO Server:
const socket = manager.socket('/')
- Add an event listener for the welcome event that expects an argument that will contain a welcome message sent by the server:
socket.on('welcome', msg => { welcome.textContent = msg })
- Add an event listener for the updateClientCount event that expects an argument that will contain the number of connected clients:
socket.on('updateClientCount', clientsCount => { n.textContent = clientsCount })
- Save the file
- Open a new Terminal and run:
node rooms-server.js
- On the web browser, navigate to:
http://localhost:1337/
- Without closing the previous tab or window, on the web browser, navigate once again to:
http://localhost:1337/
- The number of connected clients in both tabs or windows should have increased to 2