Http is a stateless protocol. So, after each request cycle , a new connection needs to be established. It is ok for normal website but for chat application, we need a continuous connection to be established.Here we have code for simple socket programming with socket.io module
var socketio = require('socket.io'); var http = require('http'); var fs = require('fs'); var conn = http.createServer(function(req,res){ res.writeHead(200,{"Content-type" :"text/html"}); res.end(fs.readFileSync(__dirname+'/index.html')) }) conn.listen(8082,function(){ console.log('Connected') }) socketio.listen(conn).on('connection',function(socket){ socket.on('clientmessage',function(msg){ socket.emit("Message from client "+msg) }) })
<html> <head> <scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <scriptsrc="/socket.io/socket.io.js"></script> <script> $(function(){ variosocket = io.connect(); iosocket.on('connect', function () { $('#incomingChatMessages').append($('<li>Connected</li>')); iosocket.on('message', function(message) { $('#incomingChatMessages').append($('<li></li>').text(message)); }); iosocket.on('disconnect', function() { $('#incomingChatMessages').append('<li>Disconnected</li>'); }); }); $('#outgoingChatMessage').keypress(function(event) { if(event.which == 13) { event.preventDefault(); iosocket.send($('#outgoingChatMessage').val()); $('#incomingChatMessages').append($('<li></li>').text($('#outgoingChatMessage').val())); $('#outgoingChatMessage').val(''); } }); }); </script> </head> <body> Incoming Chat: <ul id="incomingChatMessages"></ul> <br /> <input type="text" id="outgoingChatMessage"> </body> </html>
By Pankaj Kumar Agarwal