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 :
CREATE TABLE `fbstatus`
(
`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 npm install
Here is main Server file.
var app = require("express")();
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.