How to do it...

Create a Socket.IO client application that will connect to the Socket.IO server, that you will build next, and display a welcome message sent by the server.

  1. Create a new file named io-express-view.html
  2. Add the following code:
      <!DOCTYPE html> 
      <html lang="en"> 
      <head> 
          <meta charset="UTF-8"> 
          <title>Socket.IO Client</title> 
          <script src="http://localhost:1337/socket.io/socket.io.js">
</script> <script
src="https://unpkg.com/@babel/standalone/babel.min.js">
</script> </head> <body> <h1 id="welcome"></h1> <script type="text/babel"> const welcome = document.getElementById('welcome') const manager = new io.Manager( 'http://localhost:1337', { path: '/socket.io' }, ) const root = manager.socket('/') root.on('welcome', (msg) => { welcome.textContent = msg }) </script> </body> </html>
  1. Save the file

Next, build an ExpressJS application and a Socket.IO server. The ExpressJS application will serve the previously created HTML file on the root path "/":

  1. Create a new file named io-express-server.js
  2. Initialize a new Socket.IO server application and an ExpressJS application:
      const path = require('path') 
      const express = require('express') 
      const io = require('socket.io')() 
      const app = express() 
  1. Define the URL path where new connections will be made to the Socket.IO server:
      io.path('/socket.io') 
  1. Define a route method to serve our HTML file containing our Socket.IO client application:
      app.get('/', (req, res) => { 
          res.sendFile(path.resolve( 
              __dirname, 
              'io-express-view.html', 
          )) 
      }) 
  1. Define a namespace "/" and emit a welcome event with welcome message:
      io.of('/').on('connection', (socket) => { 
          socket.emit('welcome', 'Hello from Server!') 
      }) 
  1. Attach the Socket.IO to ExpressJS Server:
      io.attach(app.listen(1337, () => { 
          console.log( 
              'HTTP Server and Socket.IO running on port 1337' 
          ) 
      })) 
  1. Save the file
  2. Open the Terminal and run:
      node io-express-server.js
  1. In your browser, visit:
      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
3.137.217.177