Introduction to Socket.IO in NodeJS with simple example
What is Socket.IO ??
In traditional HTTP servers, when client requests for the resource then and then only the server responds. Server can not respond to user if new data is available. Disadvantage of these servers is user have to request again and again continuously in order to get new data. This increases load on server as well as user is also frustrated. Web Socket is a communication protocol which provides a full-duplex and low-latency channel between the server and the browser. It is used to implement connection between server and client such that server can also respond to client if new data is available or the old data is updated. Socket.IO is a library that enables real-time, bidirectional and event-based communication between the browser and the server.
We can connect client and server responding to each other using socket.io.
BUT Socket.IO is NOT a WebSocket implementation. Socket.IO uses WebSocket as a transport when possible, but it adds additional metadata to each packet. Due to this WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a plain WebSocket server either.
Features that socket.io provides over traditional WebSockets
- Reliability.
- Automatic Reconnection.
- Acknowledgments.
- Broadcasting to all clients or to a subset of clients (similar to Group chats).
Let’s Code
So we got enough theory knowledge of what socket.io is so let’s see a short and simple example of socket.io
Here we will built a small application which will have one screen as sender and one screen is receiver. I tried to keep things simple so a beginner can understand this easily.
Lets start by creating a Express server on Node JS. Create an empty directory and run the following command to initialize node project.
npm init
Specify some application specifications there or you can press “Enter” key and keep skipping them and keeping them as default value. Also install express and socket.io using following commands:
npm install express
npm install socket.io
Initializing Server in Index.js
Create a new file namely index.js and import some requirements.
const express = require(‘express’) // Importing Express
const app = express() // Creating Express Server
const host = ‘localhost’ // Specifying Host
const port = 8000 // Specifying Port number// Creating Http Server from Express App to work with socket.io
const http = require(‘http’).Server(app);// Initializing socket.io object
const io = require(‘socket.io’)(http,{
// Specifying CORS
cors: {
origin: “*”,
}
})
Here in the first line we are importing express library in order to create an express server in Node JS. In second line we are creating an express app using express(). Then we are specifying our host and port number. In normal express apps you usually wont create http server object. But inorder to work with socket.io we need to create instance of http server from express app. You can use express app’s methods like .get() and .post() to listen to different endpoints.
After that we are creating instance io of socket.io. It will have http object as its first parameter and other parameters are optional. We are specifying cors parameters so that currently any application can access our data. But during production time remember to allow only specific applications to read our data.
Creating endpoints using express Apps.
app.use(express.urlencoded({ extended: true })) // Specifying to use urlencoded// Creating object of Socket
const liveData = io.of(“/liveData”) // URL which will accept socket connection// Socket event
liveData.on(“user-connected”,(username)=>{
console.log(`Receiver ${username} connected..`) // Logging when user is connected
});// Get request on home page
app.get(‘/’, (req, res) => res.send(‘Hello This is our Home Page’))// Post request on home page
app.post(‘/’,(req, res) => {
liveData.emit(“new-data”,req.body.message) // Emitting event.
})// Listening on Host and Port
http.listen(port, host, () => console.log(`Listening on http://${host}:${port}/`))
Here firstly we are specifying to use urlencoded() which will help us to get form data which is send from html file. Then we are creating socket object and in them in .of() method we are specifying the url which will listen to the socket connection.
Then we are specifying an event listener which will have a callback which will be fired when the event is emitted. .on() method is used to declare event listener. First parameter is the name of the event and second parameter is the callback method. Then we are specifying get and post request on our homepage. In post request we are emitting an event called “new-data” with the data which we received from the sender. This event will be listened on client side. Then most importantly remember to call listen() method of http object not express app!!.
So far we have created a NodeJS-Express server which will listen to connections from socket.io. Now lets create the clients.
Creating Sender File
Create a new HTML file called “sender.html” and create a normal form with one input field as message as shown below.
<!DOCTYPE html>
<html lang=”en”>
<head>
<title>Sender</title>
</head>
<body>
<form action=”http://localhost:8000/" method=”post”>
<input type=”input” name=”message”>
<input type=”submit” value=”send”>
</form>
</body>
</html>
We are doing nothing special here. We are just creating a HTML form with post request to our home page.
Creating Receiver File
Now we will create a receiver HTML file. Here we will include a script from CDN which is socket.io client.
<!DOCTYPE html>
<html lang=”en”>
<head>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.js" integrity=”sha512–74AKPNm8Tfd5E9c4otg7XNkIVfIe5ynON7wehpX/9Tv5VYcZvXZBAlcgOAjLHg6HeWyLujisAnle6+iKnyWd9Q==” crossorigin=”anonymous”></script>
<title>Reciever</title>
</head>
<body>
<h1>Your messages are here</h1>
<h2 id=”msgBox”></h2>
<script>
const msgBox = document.getElementById(“msgBox”)
const socket = io.connect(“http://localhost:8000/liveData")
socket.on(“new-data”,(data)=>{
msgBox.innerHTML += (data + “<br/>”)
})
const username = prompt()
socket.emit(“user-connected”,username)
</script>
</body>
</html>
Then just before ending body tag include <script> tag and then we are getting the element by Id in msgBox. Then we should use io.connect(url) to connect to our server. Check the url if it is properly configured and matches the same url where server is hosted. Then we are creating an event listener which will listen to an event named “new-data” is event will be emitted from the server. After that we are creating a prompt to get username of the user and then we emit a socket event which will be listened on the server.
Conclusion
So this is a simple example where we are creating two separate files for sender and receiver in order to keep it simple and beginner friendly we learned how to set event Listeners and how to emit the events. I hope it was helpful to you. Have a good day ahead. Happy Learning!! Don’t forget to follow for more programming stuff :)