Socket.io is platform independent web framework which allows us to program real time bidrectional communication betweeen various devices. Using Socket.io we can build some real time application such as Live chat OR real time analytics of shares etc.
I have already covered the “event emitter” of Node.js and in this tutorial i am going to focus on covering Socket.io with simple application.
How it works ?
Socket.io is available for Node.js and also available as minified JS for client side integration so not only from Server you can emit and recieve events from Client side as well.
There are some common and most used function which you need to understand before moving ahead.
- .on : This is listener.
- .emit : This invokes and trigger the event.
For now we are using these basic function but there are more to learn ! So once the “invoker” triggers the event with some event identification particular listener or if its broadcast then every listener will catch those events and retrieve information from them.
Our application:
I am going to build simple status box which allows user to add the status and in real time update it to feeds of everyone. This is just to show how we can integrate socket.io in real time projects.
Database :
Create MySQL database name as Status and create table using following Query :
(
`status_id` INT NOT NULL AUTO_INCREMENT,
`s_text` TEXT,
`t_status` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ( `status_id` )
);
Here is our package.json.
"name" : "facebook-chat-socket",
"version" : "0.0.1",
"dependencies" : {
"express" : "~4.11.2",
"socket.io" : "~1.3.3",
"mysql" : "~2.5.5"
}
}
Install dependencies by typing
Here is main Server file.
var mysql = require("mysql");
var http = require('http').Server(app);
var io = require("socket.io")(http);
/* Creating POOL MySQL connection.*/
var pool = mysql.createPool({
connectionLimit : 100,
host : 'localhost',
user : 'root',
password : '',
database : 'fbstatus',
debug : false
});
app.get("/",function(req,res){
res.sendFile(__dirname + '/index.html');
});
/* This is auto initiated event when Client connects to Your Machien. */
io.on('connection',function(socket){
console.log("A user is connected");
socket.on('status added',function(status){
add_status(status,function(res){
if(res){
io.emit('refresh feed',status);
} else {
io.emit('error');
}
});
});
});
var add_status = function (status,callback) {
pool.getConnection(function(err,connection){
if (err) {
callback(false);
return;
}
connection.query("INSERT INTO `status` (`s_text`) VALUES ('"+status+"')",function(err,rows){
connection.release();
if(!err) {
callback(true);
}
});
connection.on('error', function(err) {
callback(false);
return;
});
});
}
http.listen(3000,function(){
console.log("Listening on 3000");
});
Here is our client side code.
<head>
<title>Socket.io</title>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script src = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
var socket = io();
$("#add_status").click(function(){
socket.emit('status added',$("#comment").val());
});
socket.on('refresh feed',function(msg){
$("#show_comments").append(msg + '<br /><br />');
});
});
</script>
</head>
<body>
<div id="comment_box" style = "padding:5%;">
<textarea id="comment" rows="5" cols="70"></textarea><br /><br />
<input type="button" id="add_status" value="Add Status">
</div>
<div
id = "show_comments"
class = "jumbotron"
style = "width: 38%;
height: 100%;
padding: 2%;
margin-left:5%;
margin-top:-53px;"
>
</div>
</body>
</html>
Output :
Run the program using
Visit “http://localhost:3000” to view the app. Open up one more window and see the updates on each window automatically.
Check the database, you can see the entries there !
Conclusion :
You can develop really cool apps using Socket.io. I am not sure though but i think Facebook comments and Twitter home page which updates the tweets as soon as someone tweet is some how related or integrated the Socket.io. Let me know if you have already built any app using this !