The era of static websites has passed. Now users demand dynamic content and application like look and feel. Instead of constantly reloading the page and hitting F5, the page should adjust itself automatically. Many of this can be accomplished with simple asynchronous requests from javascript. But what if you want to update your app only when there is a new data available on the server?
You could send a ton of requests in a loop but that’ll use a lot of bandwidth and with more users could potentially DDoS your server or make it very slow. Web technologies are constantly evolving so it’s not exceptional that we have a solution for this problem. It’s called WebSockets.
Websockets allows us to establish a stateful connection between browser and server so we can exchange pieces of information in both directions. It’s more efficient than standard request and response cycle from HTTP.
Unfortunately, WebSockets are handled differently on different browsers so it’s not easy to implement the cross-browser code. And how about older browsers that don’t support WebSockets? We need some kind of wrapper that will work on different browsers and fallback to polling techniques on older ones. Socket.io does exactly that and also provides nice API and many additional features like broadcasting.
Installation
Socket.io is split into two components client and server libraries. Both written in javascript. I assume that you have nodejs and npm installed. If not just follow instructions on the internet.
Create a directory for server code and run npm init to create package.json file for the project. Next, add the socket.io library to your project by running
npm install --save socket.io
We’ll also need express library to make things simple. Installation is as simple as typing
npm install --save express
Echo server
Let’s start with something simple.
I think echo server should be enough to demonstrate how easy it is to use socket.io, you can easily extend this example to something more complex.
Create a file called server.js and paste this code.
var http = require('http') var express = require('express') var socketio = require('socket.io') var app = express(server) var server = http.Server(app) var io = socketio(server) app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html') }); io.on('connection', function(socket){ socket.on('echo', function(data){ socket.emit('echo', data); }); }); server.listen(8080);
server.js
On first three lines, we require libraries that we are going to use. Next, we create HTTP server and express application to be able to define routes easily. You can find more about express framework on its website https://expressjs.com/ . Also, we need to create an instantiate socket.io and assign it to the server to allow WebSocket communication.
In the next line, we are using express to define root route (‘/’) to return the content of index.html file. We will store our client code there just to make things really simple. After that, we use previously created io object to listen on connection event. Every time someone connects to the server via socket.io it’ll trigger the callback function. Inside connection callback, we have access to a socket that is connected to the client. From here we can emit events or listen to them.
Let’s listen to echo event and resend the same payload by emitting echo event to the client. Note that the name echo is our custom event’s name. We don’t need to declare it anywhere so that’s convenient. The last line actually starts the server to listen on port 8080.
Client code
Create index.html file in project’s root directory and paste the following code.
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>Echo server</title> <script src="socket.io/socket.io.js"></script> <script type="text/javascript"> var socket = io(); socket.on('echo', function(data){ console.log(data); }); socket.emit('echo', 'this is a message'); </script> </head> <body> </body> </html>
The first thing you want to do is to include socket.io library. The file will be served from nodejs server so you can access it. We are adding javascript inside HTML just to make this really simple but you shouldn’t do that in production code.
Inside the code we are creating a connection to the socket.io server by calling io() function. Next, we are emitting echo event with test as a payload. Now just start the server with nodejs server.js and connect to it by accessing 0.0.0.0:8080 from your browser. You should see the this is a message message in the console immediately.
Conclusion
I think that the most important skill for a software developer is to quickly adapt to new technologies and to always pick the right tool for the task.
Socket.io is really nice and simple. It allows us to easily consume WebSockets in any application. It’s great to have it in the toolbox.
Hire Node.js Developer from us, as we give you high quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop the custom web app using Node.js, please visit our technology page.
Content Source:
- netguru.co