How to do it...

Build a Socket.IO server that will notify all the connected clients to the "commonRoom" room when a new socket is connected.

  1. Create a new file named rooms-server.js
  2. 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() 
          } 
      }) 
  1. Specify the path where new connections will be made:
      io.path('/socket.io') 
  1. Use the root namespace to listen for events:
      const root = io.of('/') 
  1. 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, 
              ) 
          }) 
      } 
  1. 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() 
      }) 
  1. 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' 
          ) 
      })) 
  1. 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:

  1. Create a new file named rooms-client.html
  2. 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>
  1. Inside the script tag, add code in the following steps, starting from step 4
  2. 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') 
  1. Define a Socket.IO Client Manager:
      const manager = new io.Manager( 
          'http://localhost:1337', 
          { path: '/socket.io' }, 
      ) 
  1. Use the root namespace which is the one used in the Socket.IO Server:
      const socket = manager.socket('/') 
  1. 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 
      }) 
  1. 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 
      }) 
  1. Save the file
  2. Open a new Terminal and run:
      node rooms-server.js
  1. On the web browser, navigate to:
      http://localhost:1337/
  1. Without closing the previous tab or window, on the web browser, navigate once again to:
      http://localhost:1337/
  1. The number of connected clients in both tabs or windows should have increased to 2
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.42.158