node socket.io+jade $ express chat $ cd chat $ npm install $ npm install --save socket.io $ vim views/layout.jade script(src='/socket.io/socket.io.js') in client javascript console socket = io.connect('http://localhost:3000') -------------------- To send message $ vim views/layout.jade script(src='/socket.io/socket.io.js') script(type='text/javascript'). socket = io.connect('http://localhost:3000') socket.on('entrance', function(data){ document.write('<p>'+data.message+'</p>'); }); socket.on('exit', function(data){ document.write('<p>'+data.message+'</p>'); }); $ vim ./bin/www.js var io = require('socket.io') var server = app.listen(......... var chatroom = io.listen(server); chatroom.sockets.on('connection', function(socket){ //socket.io's event socket.emit('entrance', {message:'Welcome to chat!'}); // our own event given to specific socket chatroom.sockets.emit('entrance', {message:'A new chatter is online.'}); // given to all sockets socket.on('disconnect', function(){ chatroom.sockets.emit('exit', {message:'A chatter disappeared!'}); }) }); every time a new client comes in a new paragraph is added To pass texts socket.on('chat', function(data){ document.write('<p>'+data.message+'</p>'); }); socket.on('chat', function(data){ chatroom.sockets.emit('chat', {message:'# '+data.message}); }) then in dev tools socket.emit('chat',{message:'hola!'}) To have a dynamic interface just copy and paste index.html and jquery to public directory <html> <head> <script src="http://localhost:3000/socket.io/socket.io.js"></script> <script src="jquery-1.7.2.min.js"></script> <script type="text/javascript" charset="utf-8"> jQuery(document).ready(function () { var log_chat_message = function (message) { var li = jQuery('<li />').text(message); jQuery('#chat_log').append(li); }; var socket = io.connect('http://localhost:3000'); socket.on('entrance', function (data) { log_chat_message(data.message); }); socket.on('exit', function (data) { log_chat_message(data.message); }); socket.on('chat', function (data) { log_chat_message(data.message); }); jQuery('#chat_box').keypress(function (event) { if (event.which == 13) { socket.emit('chat', {message: jQuery('#chat_box').val()}); jQuery('#chat_box').val(''); } }); }); </script> <style type="text/css" media="screen"> div#chatroom { display: block; height: 300px; border: 1px solid #999; overflow: auto; width: 100%; margin-bottom: 10px; position: relative; } ul#chat_log { list-style: none; position: absolute; bottom: 0px; } input#chat_box { width: 99%; } </style> </head> <body> <div id="chatroom"> <ul id="chat_log"> </ul> </div> <input type="text" name="chat_box" value="" id="chat_box" placeholder="type to chat..." /> </body> </html> instead of just logging you can format by color or bold based on kind of message make this chat system as a module
integrating node with wordpress, drupal, jumla to use their authorization, .... to add chat there |