Socket for beginners (Node.js)

Ashiq
Updated 8 Jun 2021
HIGHLIGHTS
  • Basic of socket.io
  • Code to start a socket server
  • Emit data from server on an interval

We use lot of applications in our daily life that shows us realtime data. Ever wonders how do they work? Ever tried to build anything such like that? Let me introduce you with socket. We will be using socket.io which enables real-time bidirectional event-based communication. It works on every platform, browser or device, focusing equally on reliability and speed. It is built on top of the WebSockets API (Client side) and Node.js. Here we will be developing a very basic socket application as of now.

Before you scroll let me warn you. You must have basic knowledge of javascript and have tried node.js atleast once. Well its not hard, since I will not be explaing every bits and bytes so having bit knwoledge of js is recommended.

Required

  1. Basic understanding of javascript
  2. Expericence with node.js projects
  3. Lil bit, basic idea about socket


Start a fresh prject in node.js

npm i -y


Install the requried packages

npm i express socket.io


Basic setup of our server.js file

const express = require('express');
const app = express();
var http = require('http').Server(app);

http.listen(3000, function() {
   console.log('listening on port:3000');
});

That's it now your node.js project is running and is accessible from browser using localhost:3000. So next let's serve a static html file which is located in static folder on the project directory. If you are still in confusion take help from the below repesentation


Project structure

┬socket (root folder)
├─node_modules
├┬static
│└─index.html
└─server.js


Send static HTML file when nagivated to root directory

app.get('/', function(req, res) {
   res.sendFile(__dirname + '/static/index.html');
});

Boom boom now you will be able see the index page from localhost:3000. Make sure to create a blank html file inside the static folder

All done now lets write the code for socket. First import the socket.io package then start listening events using io.on.


Setup socket, and emit data every 4 second

var io = require('socket.io')(http);

	io.on('connection', function(socket) {

    //Send a message after a timeout of 4 sec
    setInterval(function() {
        let data = { mgs: 'Emitted from server :'+new Date().getSeconds()}
        socket.emit('test', data);
    }, 4000);

});

In this sample of code we ae listening to client's request for connection to our socket and then sent data every 4 sec to the connected client from server. Let write some code for html file also, IN html filw we will connect to our socket server and listen to an event named test. When ever server will send any data to test event this client will receive the data from browser.


index.html file write the code for client side

var socket = io();
  socket.on('test', function(data){
    console.log(data);
  });

If you face any problem during setting up and running the project take reference from the below codes


server.js complete file

const express = require('express');
const app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);


//send the static html when navigated to root directory
app.get('/', function(req, res) {
   res.sendFile(__dirname + '/static/index.html');
});



io.on('connection', function(socket) {

    //Send a message after a timeout of 4 sec
    setInterval(function() {
        let data = { mgs: 'Emitted from server :'+new Date().getSeconds()}
        socket.emit('test', data);
    }, 4000);

});



http.listen(3000, function() {
   console.log('listening on port:3000');
});


index.html complete file

<!DOCTYPE html>
<html>
<body>


<script src = "/socket.io/socket.io.js"></script>
<script>
var socket = io();

socket.on('test', function(data){
	console.log(data);
});

</script>
</body>
</html>

Doubt?

If you get any doubt do let me know I will try as much I can to help you out. This was all about basics of socket (tip of ice berg), there is much more that we can do with socket. In comming days I will be writing post on advance topics like accessing socket events from controllers/services or from anywhere the node.js project, How to handle data emission on client side and much more exciting topic.


Additional resources

  1. Getting started with MQTT (Light weight and alternate of socket)
  2. Download code (Github)