Socket.io has two parts: client-side and server-side. Both parts have an identical API.
It is very easy to do bi-directional communication between browser and server. Whenever an incident occurs, the server automatically sends the message to the client. It does not require any tracking on the timestamp.
It is easy to create a chat server with more sockets.IO than the traditional PHP way. If you want to create a chat server, you have to write more lines of code in PHP.
Prerequisites of the socket.io
The latest Socket.IO release is the npm version (3.1.1). Before installing a socket, you need to ensure whether Node.js and npm are installed in your system or not. If the node.js and npm are not installed in your system, you need to install them first.
Follow these steps to install socket.io:
Step 1: Open the terminal and create a directory that name is socketio
Step 2: Initialize the npm package manager in that directory.
Step 3: Type this command to install the socket and save it.
If the user installs a specific version of the socket.io, use this command.
Real-time applications of the Socket.io
Features of Socket.IO
Socket.io serves based on some events. The socket object can be used to access some reserved events on the server-side as well as the offline side.
These are the following server-side events:
These are the following client-side events:
In this example, we have used connection and disconnection events to log-in when a user has connected and disconnected.
After Four seconds when the client connects, the server will send the client an event called a message.
Now, we have to handle this event on behalf of our client, so modify the index.html script tag to include the following code:
When the server sends the message event to the client after 4 seconds, the client will handle it and produce the output. This output is shown in the screenshot below.