Continuing my exploration on Node.js – I started working on the server push. I had read that socket.io (a node.js module).
Since I had node installed in my Ubuntu 12.10 (64-bit) – I was able to get the basic example done in 5 minutes.
1. Create a directory serverpush and go into that directory
sai@sai-home:~$ mkdir serverpush
sai@sai-home:~$ cd serverpush/
2. Create a package.json in the serverpush directory
{
“name”: “serverpush”,
“version”: “0.0.1”,
“private”: true,
“scripts”: {
“start”: “node app”
},
“dependencies”: {
“socket.io”: “~0.9.6”
},
“engines”: {
“node”: “0.8.x”
}
}
3. To install all dependancies – we need to use npm (node package manager) that uses the information in package.json
sai@sai-home:~/serverpush$ npm install -d
The above command installed all missing dependencies
4.Next is to create the node.js server file called app.js
var app = require(‘http’).createServer(handler)
, io = require(‘socket.io’).listen(app)
, fs = require(‘fs’)
app.listen(8888);
function handler (req, res) {
fs.readFile(__dirname + ‘/index.html’,
function (err, data) {
if (err) {
res.writeHead(500);
return res.end(‘Error loading index.html’);
}
res.writeHead(200);
res.end(data);
});
}
function sendData(socket){
var thisRef = this;
var currentTimeObj = new Date();
// though there are better ways to format time – living with this for the time being
var formattedTime = currentTimeObj.getDate() + “-” +currentTimeObj.getMonth() + “-” + currentTimeObj.getFullYear() + ” ” + currentTimeObj.getHours() + “:” + currentTimeObj.getMinutes() + “:” + currentTimeObj.getSeconds();
socket.emit(‘timeUpdate’, { currentTime: formattedTime});
setTimeout(function(){
sendData.call(thisRef,socket)
},1000);
}
io.sockets.on(‘connection’, function (socket) {
socket.emit(‘welcomeMessage’, { welcome: ‘Welcome to server poller’ });
sendData(socket);
});
4. Create the index.html that will be used as the client code
<!DOCTYPE html>
<html>
<head>
<title>Server Time poller</title>
<meta charset=”UTF-8″>
</head>
<body>
<div id=”statusMessageDiv”>
</div>
<div id=”serverTimeDiv”></div>
</body>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js”></script>
<script src=”/socket.io/socket.io.js”></script>
<script>
$(document).ready(function(){
var socket = io.connect(‘http://localhost’);
socket.on(‘welcomeMessage’,function(data){
$(“#statusMessageDiv”).html(data.welcomeMessage);
});
socket.on(‘timeUpdate’, function (data) {
$(“#serverTimeDiv”).html(data.currentTime);
});
});
</script>
</html>
5. Run the server file using node
sai@sai-home:~/serverpush$ node app.js
info – socket.io started
6. Launch the server through browser http://localhost:8888 – we will see our server time running
That’s it – really amazed at the productivity with Node.js
Planning to use server push to write a twitter clone next 🙂