Topics
i) Importing libraries
ii) Create Server and Handle Request
iii) Play with Socket.io to do MultiChatting
2) Develop Webpage with Socket Javascript
3) Download Project here
1) Code your Server.js - Node.js main file
i) Importing libraries
var http = require("http"); var url = require('url'); var fs = require('fs'); var io = require('socket.io');
ii) Create Server and Handle Request
var server = http.createServer(function(request, response){ var path = url.parse(request.url).pathname; console.log('Path='+path); switch(path){ case '/': fs.readFile(__dirname + "/index.html", function (error, data) { if (error) { response.writeHead(404); response.write("opps this doesn't exist - 404"); response.end(); } else{ response.writeHeader(200, {"Content-Type": "text/html"}); response.write(data, "utf8"); response.end(); } }); break; case '/socket.html': fs.readFile(__dirname + path, function (error, data) { if (error) { response.writeHead(404); response.write("opps this doesn't exist - 404"); response.end(); } else{ response.writeHeader(200, {"Content-Type": "text/html"}); response.write(data, "utf8"); response.end(); } }); break; default: console.log(path +"- Not found"); response.writeHead(404); response.write("opps this doesn't exist - 404"); response.end(); break; } }); server.listen(8001);
iii) Play with Socket.io to do MultiChatting
var serv_io = io.listen(server); var textarea=""; var name=""; serv_io.sockets.on('connection', function(socket){ //send data to client setInterval(function(){ socket.emit('date', {'date': getCurrentTime()} ); }, 1000); socket.on('client_data', function(data){ textarea=data.textarea; name=data.name; console.log("name="+name); //socket.emit('textarea', {'textarea': data.textarea}); emitData(socket); }); }); function emitData(socket){ socket.broadcast.emit('message', {'date': getCurrentTime(), 'name' : name, 'textarea':textarea } ); } function getCurrentTime(){ var d = new Date(); var curr_date = d.getDate(); var curr_month = d.getMonth()+1; var curr_year = d.getFullYear(); var curr_hour = d.getHours()%12 +""; var curr_min = d.getMinutes() + ""; var curr_sec = d.getSeconds() + ""; if(curr_hour.length == 1) curr_hour="0"+curr_hour; if(curr_min.length == 1) curr_min="0"+curr_min; if(curr_sec.length == 1) curr_sec="0"+curr_sec; //var dateString = sprintf("%2s-%2s-%s %2s:%2s:%2s ",curr_date,curr_month,curr_year,curr_hour,curr_min,curr_sec); var dateString = curr_date + "-" + curr_month + "-" + curr_year + " " + curr_hour +":"+ curr_min +":"+ curr_sec; return dateString; }
2) Develop Webpage with Socket Javascript
<html> <head> <script src="/socket.io/socket.io.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script> <style> .common{ width: 200px; height: 30px; padding-left: 10px; } #date{ color: green; } </style> </head> <body> <script> var socket = io.connect(); socket.on('date', function(data){ $('#date').text(data.date); }); socket.on('message', function(data){ message=data.textarea; len=message.length; if(len > 0){ printMessage(data.name,message); } }); $(document).ready(function(){ $('#textarea').keypress(function(e){ if ( event.which == 13 ) { message=$('#textarea').val(); len=message.length; strname = $('#name').val(); if(len > 0){ socket.emit('client_data', {'name':strname,'textarea': message}); printMessage(strname,message); } $('#textarea').val(""); } }); }); function printMessage(strname,message){ $('#messagearea').html($('#messagearea').html()+"<br/><span style='color:blue;font:18px;'>"+strname+"</span> : "+message); } </script> <div><h1>Welcome to Node.js Socket.io - Simple Multi Chat Application</h1></div> <b> Get tutorial here (Post your comments and query)</b> - <a href='http://www.coolcomputerpctricks.com'>www.coolcomputerpctricks.com</a><br><br> <b> Get Latest Code here </b> - <a href='https://github.com/karthikeyan98'>https://github.com/karthikeyan98</a> <br><br>Current Time: <span id="date"></span><br/> <input type="text" id="name" value="Guest" class="common"> - Type Name here<br/><br/> <textarea id="textarea" class="common"></textarea> - Type Message here and press Enter. <div id="messagearea"></div> </body> </html>
3) Download Project here
GitHub - https://github.com/karthikeyan98/SimpleMultiChatPost your comments and query for any help.
Developing your first Node.js Socket io application - Learn Simple Multichat example in Node.js and socket.io.