How to do it...

Build a Socket.IO server that will fire a data event and send an object containing two properties, title and msg, that will be used to populate HTML content in the selected language. Use namespaces to separate and send different data according to the language that the client chooses, English or Spanish.

  1. Create a new file named nsp-server.js
  2. Include the Socket.IO npm module and the required modules for creating an HTTP server:
      const http = require('http') 
      const fs = require('fs') 
      const path = require('path') 
      const io = require('socket.io')() 
  1. Use the http module to create a new HTTP server that will serve an HTML file you will create later as a Socket.IO client:
     const app = http.createServer((req, res) => { 
      if (req.url === '/') { 
               fs.readFile( 
               path.resolve(__dirname, 'nsp-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 new connections will be made to:
      io.path('/socket.io') 
  1. For the "/en" namespace, add a new event listener, getData, which when fired will emit a data event on the client side and send an object including a title and a msg property in the English language:
     io.of('/en').on('connection', (socket) => { 
        socket.on('getData', () => { 
            socket.emit('data', { 
               title: 'English Page', 
               msg: 'Welcome to my Website', 
           }) 
        }) 
   }) 
  1. For the "/es" namespace, do the same. However, the object sent to the client will include a title and a msg property in the Spanish language:
      io.of('/es').on('connection', (socket) => { 
          socket.on('getData', () => { 
              socket.emit('data', { 
                  title: 'Página en Español', 
                  msg: 'Bienvenido a mi sitio Web', 
              }) 
          }) 
      }) 
  1. Listen on port 1337 for new connections and attach Socket.IO to the underlying HTTP server:
      io.attach(app.listen(1337, () => { 
          console.log( 
              'HTTP Server and Socket.IO running on port 1337' 
          ) 
      })) 
  1. Save the file.

Afterwards, create a Socket.IO client that will connect to our server and populate HTML content based on the data received from the server.

  1. Create a new file named nsp-client.html
  2. First, specify the document type as HTML5. Next to it, add an html tag and set the language to English. Inside the html tag, include the head and body tags as well:
      <!DOCTYPE html> 
      <html lang="en"> 
      <head> 
          <meta charset="UTF-8"> 
          <title>Socket.IO Client</title> 
      </head> 
      <body> 
          <!-- code here --> 
      </body> 
      </html> 
  1. Inside the body tag, add the first three elements: a heading (h1) that will contain the title of the content, a p tag that will include a message from the server, and a button that will be used to switch to a different namespace. Also, include the Socket.IO client library. The Socket.IO server will make the library file available at this URL: http[s]://host:port/socket.io/socket.io.js . Then, also include as well the babel standalone library which will transform the code in the next steps into JavaScript code that can run in all browsers:
      <h1 id="title"></h1> 
      <section id="msg"></section> 
      <button id="toggleLang">Get Content in Spanish</button> 
       <script src="http://localhost:1337/socket.io/socket.io.js">  
</script> <script src="https://unpkg.com/@babel/standalone/babel.min.js">
</script>
  1. Inside the body, after the last script tags, add another script tag and set its type to "text/babel":
      <script type="text/babel"> 
          // code here! 
      </script> 
  1. After that, inside the script tag, add the following JavaScript code
  2. Define three constants that will contain a reference to the elements we have created in the body:
      const title = document.getElementById('title') 
      const msg = document.getElementById('msg') 
      const btn = document.getElementById('toggleLang') 
  1. Define a Socket.IO client manager. It will help us to create sockets with the provided configuration:
      const manager = new io.Manager( 
          'http://localhost:1337', 
          { path: '/socket.io' }, 
      ) 
  1. Create a new socket that will connect to the "/en" namespace. We will assume that this is the default connection:
      const socket = manager.socket('/en') 
  1. Reserve two connections for namespaces "/en" and "/es". A reserved connection will allow us to switch to a different namespace without the need of to create a new TCP connection:
      manager.socket('/en') 
      manager.socket('/es') 
  1. Add an event listener that, once the socket is connected, will emit a getData event to request data from the server:
      socket.on('connect', () => { 
          socket.emit('getData') 
      }) 
  1. Add an event listener for the data event that will get triggered when the client received data from the server:
      socket.on('data', (data) => { 
          title.textContent = data.title 
          msg.textContent = data.msg 
      }) 
  1. Add an event listener for the button. When it gets clicked, switch to a different namespace:
      btn.addEventListener('click', (event) => { 
          socket.nsp = socket.nsp === '/en' 
              ? '/es' 
              : '/en' 
          btn.textContent = socket.nsp === '/en' 
              ? 'Get Content in Spanish' 
              : 'Get Content in English' 
          socket.close() 
          socket.open() 
      }) 
  1. Save the file
  2. Open a new terminal and run:
      node nsp-server.js
  1. In the web browser, navigate to:
      http://localhost:1337/
..................Content has been hidden....................

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