Web Sockets allow us to set up bi-directional persistent communication channels between two or more machines at a time.
socket.io
, we need node.js
and NPM
.
We can test it using the following commands respectively:
>node --version
v8.5.0
>npm --version
5.4.2
socket.io
using the following command :
>npm install socket.io
Real-Time Quotes
app using socket.io
node.js
, socket.io
, express.js
, HTML5
,
CSS3
, and little bit of jquery
. In our real-time quotes
app , We update the quotes in real-time on all the tabs where
index.html
page is open. The updation of quotes is done from the admin.html
file which is further using sockets under the hood.It is explained
in detail along with its code below.
index.html
File ( CSS
included ) admin.html
File ( CSS
included ) server.js
for backend index.html
frontend file : This is the file which end users will see. All the quotes updated by the admin
are displayed here. We are using blockquote
tags of HTML to display the quotes.
Although the code is self-explanatory but informative comments are given whereever required.
<html>
<head>
<title> Real Time Quotes | Nodejsera </title>
<!-- Including google font Josefin Sans -->
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans|Josefin+Slab" rel="stylesheet">
<!-- Including bootstrap v3.3.7 -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- Including jquery v3.2.1 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Including socket.io file v2.0.3 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<!-- Custom CSS to make it presentable -->
<style>
.font{
font-family: 'Josefin Slab', serif;
text-align:center;
font-size: 40px;
font-weight:bold;
}
blockquote{
font-family: 'Josefin Sans', sans-serif;
background:#ccccff;
font-size: 30px;
font-weight: normal;
border-left: 4px solid #4db8ff;
}
</style>
</head>
<body>
<div class="container">
<div class="col-md-2">
</div>
<div class="col-md-8">
<!-- Heading -->
<div class="font"> Real Time Quotes </div>
<hr>
<!-- Default quote -->
<div class="quotes" id="quotes">
<blockquote> have a great day , have a great life </blockquote>
</div>
</div>
<div class="col-md-2">
</div>
</div>
<script>
//Jquery code starts here
$('document').ready(function(){
//Connecting the socket to host and port
var socket = io.connect('http://localhost:3000');
//Test event
//Users can skip it.
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
//Test event ends here
//Main event "next"
socket.on('next' , function(data) {
console.log(data);
$('#quotes').append("<blockquote>" + data.data.quote + "</blockquote>")
})
//Event ends
});
//jquery code ends here
</script>
</body>
</html>
admin.html
frontend file : This file is used by the admin
to update the quotes. Admin
add the quote to be added in the textarea
tag of the HTML and then clicks the Add yoyr quote
button and
it will emit an socket event. The task of the event is to pass the data to the server. The code is given below with informative
comments :
<html>
<head>
<title> Real Time Quotes | Admin Panel | Nodejsera </title>
<!-- Including google font Josefin Sans -->
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans|Josefin+Slab" rel="stylesheet">
<!-- Including bootstrap v3.3.7 -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- Including jquery v3.2.1 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Including socket.io file v2.0.3 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<!-- Custom CSS to make it look presentable -->
<style>
.font{
font-family: 'Josefin Slab', serif;
text-align:center;
font-size: 40px;
font-weight:bold;
}
textarea {
font-family: 'Josefin Slab', serif;
width: 100%;
min-height: 100px;
font-size: 40px;
padding: 12px 20px;
margin: 8px 0;
border: 2px solid #4db8ff;
}
input[type=button]{
font-family: 'Josefin Slab', serif;
width: 100%;
background-color: #4db8ff;
border: none;
color: white;
font-size: 30px;
padding: 16px 32px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
border-radius: 15px;
}
input:hover{
background-color: #008ae6;
}
input:focus,
textarea:focus,
button:focus {
outline: none;
}
</style>
</head>
<body>
<div class="container">
<div class="col-md-3">
</div>
<div class="col-md-6">
<!-- Heading -->
<h1 class="font">
Add Your Quotes in Realtime using <code> Sockets</code> and <code> node.js </code>
</h1>
<hr>
<div>
<!-- Text area where admin will write quote -->
<textarea id="qcontent"></textarea>
<br>
<br>
<!-- Quotes Tranferred to server when button is clicked via "new" event-->
<div>
<input type="button" id="aquote" value="Add your Quote"> </button>
</div>
</div>
</div>
<div class="col-md-3">
</div>
</div>
<script>
//Jquery code starts
$('document').ready(function(){
//Connecting the socket to host and port
var socket = io.connect('http://localhost:3000');
socket.on('welcome', function (data) {
});
$('#aquote').click(function(){
data = $('#qcontent').val()
console.log(data);
//Emitting the event and passing the quote to the server
socket.emit('new' , { quote: data })
$('#qcontent').val('');
})
})
//jquery code ends
</script>
</body>
</html>
server.js
backend file : The server will receive the event emitted by the admin
file along with the
quote and will emit an event for the index
file passing the quotes. And finally the quote will be displayed on index
file.
//Including the required files
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
//server listening at 127.0.0.1:3000
server.listen(3000);
console.log("Server listening at: 3000");
//Handling the default route
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
//Handling the route for admin
app.get('/admin' , function(req,res) {
res.sendFile(__dirname + '/admin.html');
})
//Code for sockets
io.on('connection', function (socket) {
socket.emit('welcome', { data: 'welcome' });
socket.on('new' , function(data) {
console.log('About to upload Quote')
io.sockets.emit( 'next' , { data : data } )
})
});
>node server.js
index.html
page. Changing css Dynamically
app using socket.io
Changing css dynamically
app is used to change the background color of all the paragraph tags of css-color.html
file by selecting the color
on the css-color-admin.html
file which is our admin file. All this is achieved with the help of an node.js server. The server is built
using node.js
, express.js
and socket.io
. It is explained in more detail below.
css-color.html
File ( CSS
included ) css-color-admin.html
File ( CSS
included ) server.js
for backend css-color.html
frontend file : This file contains some random text which is written within p
paragraph tags.
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans|Josefin+Slab" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<style>
h2{
font-family: 'Josefin Slab', serif;
text-align:center;
font-size: 40px;
font-weight:bold;
}
p{
font-family: 'Josefin Sans', sans-serif;
font-size: 30px;
font-weight: normal;
padding : 30px;
}
h3{
font-family: 'Josefin Sans', sans-serif;
font-size: 30px;
font-weight: normal;
padding : 30px;
}
</style>
</head>
<body>
<div class="row">
<div class="col-md-2">
</div>
<div class="col-md-8">
<h2>Changing CSS Dynamically using Socket.io</h2>
<br>
<br>
<p style="background-color:#00aaff">A Normal </p>
<p style="background-color:#aaff00">text paragraph in which </p>
<p style="background-color:#aa00ff">we are using sockets to change CSS</p>
<p>dynamically from the admin panel</p>
<h3> But it will only change the CSS of content which is inside <code> p (paragraph) </code> tag.</h3>
</div>
<div class="col-md-2">
</div>
</div>
<script>
$(document).ready(function(){
var socket = io.connect('http://localhost:3000');
socket.on('color' , function(data) {
console.log(data);
var key= "background-color";
var value = data.data.color;
$("p").css(key, value);
})
});
</script>
</body>
</html>
css-color-admin.html
frontend file : Admin can select the background color from the color picker here and the launch
the event with the button click.
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans|Josefin+Slab" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<style>
input[type=color]{
width:100%;
height:20%;
cursor: pointer;
border-color: 4px solid #f4b942;
}
input[type=button]{
font-family: 'Josefin Slab', serif;
width : 100%;
border: none;
color: #fff;
font-size: 30px;
padding: 16px 32px;
text-decoration: none;
margin: 4px 2px;
border-radius: 15px;
font-weight:bold;
background-color: #3558a8;
}
input[type=button]:hover{
cursor: pointer;
background-color: #a4b9e8;
color:#fff;
}
h1{
font-family: 'Josefin Slab', serif;
text-align:center;
font-size: 40px;
font-weight:bold;
}
</style>
</head>
<body>
<div class="row">
<div class="col-md-4">
</div>
<div class="col-md-4">
<span class="actions">
<h1> Click Here to Pick Color</h1>
<input id="color" name="Color Picker" type="color" value="Pick Color"/>
<input type="button" class="btn" id="btn" value="Emit an Event" />
</span>
</div>
<div class="col-md-4">
</div>
</div>
<script>
var socket = io.connect('http://localhost:3000');
( function(){
console.log('I am a self executing function');
var myfunc = function(){
console.log('admin emitted an event ');
var color = $("#color").val();
console.log(color);
socket.emit('admin', { color: color });
}
document.getElementById('btn').onclick = myfunc;
})();
</script>
</body>
</html>
server.js
backend file : Server receives the event from admin file and emits and event for the css-color.html
file.
//Including the required files
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
//server listening at 127.0.0.1:3000
server.listen(3000);
console.log("Listening at 3000");
//Handling the default route
app.get('/', function (req, res) {
res.sendFile(__dirname + '/css-color.html');
});
//Handling the route for admin
app.get('/admin' , function(req,res) {
res.sendFile(__dirname + '/css-color-admin.html');
})
//Code for sockets
io.on('connection', function (socket) {
socket.on('admin' , function(data) {
console.log(data);
console.log('about to broadcast')
io.sockets.emit( 'color' , { data : data } )
})
});
>node server.js
In this chapter of 30 days of node tutorial series, we learned about the basics of sockets, their features , prerequisites and installation. After that we dive deep into sockets by writing 2 live working projects in sockets.