Chat webapp with node.js
I was particularly interested to understand how the socket plug-in works in Node.js. The goal of this blog post is to explain to you how to great a basic chat system.
Assumption:
- node.js installed (https://github.com/joyent/node/wiki/Installation)
I recommend you to use the latest stable version (0.6.15)
If it's your first time with node.js I recommend you to follow the excellent tutorial for beginner: http://www.nodebeginner.org/
Fine, now you have your node.js server up and running, let's begin.
We are going to use two files: server.js which will be our backend part. And client.html, the frontend.
So, create the web server and read the html file.
server.js
// Require dependencies var app = require('http').createServer(handler) , fs = require('fs'); // creating the server ( localhost:8000 ) app.listen(8000); // on server started we can load our client.html page function handler ( req, res ) { fs.readFile( __dirname + '/client.html' , function ( err, data ) { if ( err ) { console.log( err ); res.writeHead(500); return res.end( 'Error loading client.html' ); } res.writeHead( 200 ); res.end( data ); }); }
<html> <body> <h1>Welcome on the chat</h1> </body> </html>
Start the server and let's look if we have something here: http://localhost:8000/
Terminal
node server.jsNow we have a web server running and a page is displayed. Great but it's not enough. Let's continue by asking the user his nickname and store it. It's required to have the socket.io plug-in.
Terminalnpm install socket.io<html> <body> <h1>Welcome on the chat</h1> <!-- Include the socket.io javascript on the client side --> <script src="socket.io/socket.io.js"></script> <script> // Establish the connection with the server var socket = io.connect('http://localhost:8000'); // Create a new socket connection socket.on('connect', function() { socket.emit('set nickname', prompt('What is your nickname?')); }); </script> </body> </html>
server.js
// Require dependencies var app = require('http').createServer(handler) , fs = require('fs') , io = require('socket.io').listen(app); // creating the server ( localhost:8000 ) app.listen(8000); // on server started we can load our client.html page function handler ( req, res ) { fs.readFile( __dirname + '/client.html' , function ( err, data ) { if ( err ) { console.log( err ); res.writeHead(500); return res.end( 'Error loading client.html' ); } res.writeHead( 200 ); res.end( data ); }); } // creating a new websocket to keep the content updated without any AJAX request io.sockets.on( 'connection', function ( socket ) { socket.on('set nickname', function (nickname) { // Save a variable 'nickname' socket.set('nickname', nickname, function () { var connected_msg = nickname + ' is now connected.'; console.log(connected_msg); }); }); });
Restart the server and refresh the page to check the update. You should be prompted to enter your nickname. While submitting your nickname, check the terminal logs to see the message.:
Damien is now connected.Now, broadcast to all connected users a message when someone connect on the chat, by calling the emit() function.
server.js// Require dependencies var app = require('http').createServer(handler) , fs = require('fs') , io = require('socket.io').listen(app); // creating the server ( localhost:8000 ) app.listen(8000); // on server started we can load our client.html page function handler(req, res) { fs.readFile(__dirname + '/client.html', function(err, data) { if(err) { console.log(err); res.writeHead(500); return res.end('Error loading client.html'); } res.writeHead(200); res.end(data); }); } // creating a new websocket to keep the content updated without any AJAX request io.sockets.on('connection', function(socket) { socket.on('set nickname', function(nickname) { // Save a variable 'nickname' socket.set('nickname', nickname, function() { var connected_msg = nickname + ' is now connected.'; console.log(connected_msg); io.sockets.volatile.emit('broadcast_msg', connected_msg); }); }); });
And update the client to receive and display messages. We will also need to include jQuery.
client.html<html> <body> <h1>Welcome on the chat</h1> <ul id="broadcast-msg"></ul> <!-- Include the socket.io javascript on the client side --> <script src="socket.io/socket.io.js"></script> <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script> // Establish the connection with the server var socket = io.connect('http://localhost:8000'); // on every message recived we print the new datas inside the #broadcast-msg div socket.on('broadcast_msg', function (data) { console.log('Get broadcasted msg:', data); var msg = '<li>' + data + '</li>'; $('#broadcast-msg').append(msg); }); // Create a new socket connection socket.on('connect', function() { socket.emit('set nickname', prompt('What is your nickname?')); }); </script> </body> </html>
Again, restart the server and refresh the page to check the update.
Yeah, we have submit a string to the server and we got an answer to display on the client.
The loop is done. We can add a text field to let users enter their messages.
Moreover, on the server side, we will get the saved nickname before broadcasting the massage to all connected user.
// Require dependencies var app = require('http').createServer(handler) , fs = require('fs') , io = require('socket.io').listen(app); // creating the server ( localhost:8000 ) app.listen(8000); // on server started we can load our client.html page function handler(req, res) { fs.readFile(__dirname + '/client.html', function(err, data) { if(err) { console.log(err); res.writeHead(500); return res.end('Error loading client.html'); } res.writeHead(200); res.end(data); }); } // creating a new websocket to keep the content updated without any AJAX request io.sockets.on('connection', function(socket) { socket.on('set nickname', function(nickname) { // Save a variable 'nickname' socket.set('nickname', nickname, function() { var connected_msg = nickname + ' is now connected.'; console.log(connected_msg); io.sockets.volatile.emit('broadcast_msg', connected_msg); }); }); socket.on('emit_msg', function (msg) { // Get the variable 'nickname' socket.get('nickname', function (err, nickname) { console.log('Chat message by', nickname); io.sockets.volatile.emit( 'broadcast_msg' , nickname + ': ' + msg ); }); }); });
client.html
<html> <body> <h1>Welcome on the chat</h1> <label for="msg-input">Broadcast message</label> <input id="msg-input" name="msg-input" type="text" size="30" /> <p>Press enter to submit your message</p> <ul id="broadcast-msg"></ul> <!-- Include the socket.io javascript on the client side --> <script src="socket.io/socket.io.js"></script> <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script> // Establish the connection with the server var socket = io.connect('http://localhost:8000'); // on every message recived we print the new datas inside the #broadcast-msg div socket.on('broadcast_msg', function (data) { console.log('Get broadcasted msg:', data); var msg = '<li>' + data + '</li>'; $('#broadcast-msg').append(msg); }); // Create a new socket connection socket.on('connect', function() { socket.emit('set nickname', prompt('What is your nickname?')); $('#msg-input').change( function(){ var txt = $(this).val(); $(this).val(''); socket.emit('emit_msg', txt, function (data){ console.log('Emit Broadcast msg', data); }); }); }); </script> </body> </html>
Again, restart the server and refresh the page to check the update.
Congratulation, the base of your chat application is done.
I will finish this tutorial by adding a last feature to broadcast a message when a user disconnect from our chat.
For that I will use the reserved socket.on('disconnect', function () {});
// Require dependencies var app = require('http').createServer(handler) , fs = require('fs') , io = require('socket.io').listen(app); // creating the server ( localhost:8000 ) app.listen(8000); // on server started we can load our client.html page function handler(req, res) { fs.readFile(__dirname + '/client.html', function(err, data) { if(err) { console.log(err); res.writeHead(500); return res.end('Error loading client.html'); } res.writeHead(200); res.end(data); }); } // creating a new websocket to keep the content updated without any AJAX request io.sockets.on('connection', function(socket) { socket.on('set nickname', function(nickname) { // Save a variable 'nickname' socket.set('nickname', nickname, function() { console.log('Connect', nickname); var connected_msg = '<b>' + nickname + ' is now connected.</b>'; io.sockets.volatile.emit('broadcast_msg', connected_msg); }); }); socket.on('emit_msg', function (msg) { // Get the variable 'nickname' socket.get('nickname', function (err, nickname) { console.log('Chat message by', nickname); io.sockets.volatile.emit( 'broadcast_msg' , nickname + ': ' + msg ); }); }); // Handle disconnection of clients socket.on('disconnect', function () { socket.get('nickname', function (err, nickname) { console.log('Disconnect', nickname); var disconnected_msg = '<b>' + nickname + ' has disconnected.</b>' // Broadcast to all users the disconnection message io.sockets.volatile.emit( 'broadcast_msg' , disconnected_msg); }); }); });
For the last time, restart the server and refresh the page to check the update.
You can improve the application by adding the time of the message.
Also, the list of messages can be huge. With some jQuery kick you can kept the list bellow a define number of messages.
Thanks for ready and Keep Open Spirit.






7 reponses to "Chat webapp with node.js"
1. well this tutorial is
2. I have no clue how to do
3. .
4. I don't know what's wrong but
5. Hi, have you more information
6. Thanks, I have created a
7. Well, if your computer's IP