How to do it...

A Socket.IO server will be built to respond to a single event named time. When the event is fired, it will get the server's current time and emit another event named "got time?" providing two arguments, the current time and a counter that specifies how many times a request was made.

  1. Create a new file named simple-io-server.js
  1. Include the Socket.IO module and initialize a new server:
      const io = require('socket.io')() 
  1. Define the URL path where connections will be made:
      io.path('/socket.io') 
  1. Use the root or "/" namespace:
      const root = io.of('/') 
  1. When a new connection is made, initialize a counter variable to 0. Then, add a new listener to the time event that will increase the counter by one, every time there is a new request, and emit the "got time?" event that will be later defined on the client side:
      root.on('connection', socket => { 
          let counter = 0 
          socket.on('time', () => { 
              const currentTime = new Date().toTimeString() 
              counter += 1 
              socket.emit('got time?', currentTime, counter) 
          }) 
      }) 
  1. Listen on port 1337 for new connections:
      io.listen(1337) 
  1. Save the file

Next, build a Socket.IO client that will connect to our server:

  1. Create a new file named simple-io-client.js
  2. Include the Socket.IO client module:
      const io = require('socket.io-client') 
  1. Initialize a new Socket.IO client providing the server URL and an options object where we will define the path used in the URL where the connections will be made:
      const clientSocket = io('http://localhost:1337', { 
          path: '/socket.io', 
      }) 
  1. Add an event listener to the connect event. Then, when a connection is made, using a for loop, emit the time event 5 times:
      clientSocket.on('connect', () => { 
          for (let i = 1; i <= 5; i++) { 
              clientSocket.emit('time') 
          } 
      }) 
  1. Add an event listener to the "got time?" event that will expect to receive two arguments the time and a counter that specifies how many requests were made to the server, then print on the console:
      clientSocket.on('got time?', (time, counter) => { 
          console.log(counter, time) 
      }) 
  1. Save the file
  2. Open a Terminal and run first the Socket.IO server:
    node simple-io-server.js
  1. Open another terminal and run the Socket.IO client:
    node simple-io-client.js
..................Content has been hidden....................

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