The Socket.IO server events

Socket.IO uses a single TCP connection to a single path. That means, by default, the connection is made to the URL http[s]://host:port/socket.io. However, within Socket.IO, it allows you to define namespaces. That means, different end-points but the connection will still remain a single URL.

By default, Socket.IO Server uses the "/" or root namespace

You can, of course, define multiple instances and listen to different URLs as well. However, we will assume, for the purpose of this recipe, that only one connection is created.

The Socket.IO namespace has the following events that your application can subscribe to:

  • connect or connection: When a new connection is made, this event is fired. It provides a socket object to the listener as the first parameter that represents the new connection with the client
      io.on('connection', (socket) => { 
          console.log('A new client is connected') 
      }) 
      // Which is the same as:
io.of('/').on('connection', (socket) => { console.log('A new client is connected') })

The Socket.IO socket object has the following events:

  • disconnecting: This event is emitted when the client is going to be disconnected from the server. It provides to the listener a parameter that specifies the reason for the disconnection
      socket.on('disconnecting', (reason) => { 
          console.log('Disconnecting because', reason) 
      }) 
  • disconnected: Similar to the disconnecting event. However, this event is fired after the client has been disconnected from the server:
      socket.on('disconnect', (reason) => { 
          console.log('Disconnected because', reason) 
      }) 
  • error: This event is emitted when an error occurs within events
      socket.on('error', (error) => { 
          console.log('Oh no!', error.message) 
      }) 
  • [eventName]: A user-defined event that will get fired when the client emits an event with the same name. The client can emit an event providing data in the arguments. On the server, the event will be fired and it will receive the data sent by the client
..................Content has been hidden....................

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