Cestfait.ch

  • Home
  • Drupal
  • PHP 5
  • Jquery
  • Web Dev
  • Sys admin
  • Logiciels libres
  • Videos
  • Toi
  • Divers
  • Nous contacter
  • Mon c'est fait!
Home

Chat webapp with node.js

Submitted by dsnoeck on Thu, 04/26/2012 - 21:12
Node.js is great, if you don't know it yet check the description on nodejs.org.

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 );
  });
}
client.html
<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.js

Now 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.

Terminal
npm install socket.io
client.html
<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.

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);
    });
  });
 
 
  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 () {});

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() {
      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.

0
Log in to vote
Your rating: None Average: 5 (11 votes)
  • Login or register to post comments
  • Share this
Tags:
  • chat
  • nodejs
  • socket
  • Web Dev

7 reponses to "Chat webapp with node.js"

1. well this tutorial is

Submitted by abduIntegral on Tue, 04/23/2013 - 13:11.
well this tutorial is great. how we can get audio from default microphone using js. i need to create an audio chat app can you help
  • Login or register to post comments

2. I have no clue how to do

Submitted by dsnoeck on Tue, 04/30/2013 - 14:48.
I have no clue how to do that. Ask this question to some Node specific website.
  • Login or register to post comments

3. .

Submitted by jeev1989 on Tue, 10/16/2012 - 10:47.
.
  • Login or register to post comments

4. I don't know what's wrong but

Submitted by shekharsuman on Wed, 07/04/2012 - 19:48.
I don't know what's wrong but i'm getting a prompt only on Internet Explorer. I get a prompt on Google Chrome only when I stop the server by pressing ctrl+c. Please help!
  • Login or register to post comments

5. Hi, have you more information

Submitted by dsnoeck on Fri, 08/03/2012 - 14:32.
Hi, have you more information in the logs of the server that you can check in your terminal. You can have more information in the logs with -v or with --debug when you start your server: node -v server.js
  • Login or register to post comments

6. Thanks, I have created a

Submitted by ashwin on Fri, 06/29/2012 - 15:19.
Thanks, I have created a sample chat application using your tutorial. I am also able to connect it from different machine or different browser window. But I am not getting one thing. I have to open client.html file in the browser like this - file:///home/abcd/chatapp/client.html. What do I need to do to open a file this way - http://192.168.1.100:8000/client.html Sorry for my bad english. I will be very thankful if you could reply to my message.
  • Login or register to post comments

7. Well, if your computer's IP

Submitted by dsnoeck on Fri, 08/03/2012 - 14:41.
Well, if your computer's IP is 192.168.1.100, so I don't see any trouble to access the application like you ask! The port (:8000) is define at the beginning of the server.js file. app.listen(8000). Here you can chose whatever port you prefer, as long as it's not used by anoter application. In my case I was not able to run the application by opening the file like this: file:///home/abcd/chatapp/client.html in the browser.
  • Login or register to post comments

User login

  • Create new account
  • Request new password
  • Sign in with Twitter

Sondage

Quel framwork php utilisez vous ?

Submitted by Sir Squall on Tue, 12/11/2012 - 18:07
  • Login or register to post comments

Recent comments

  • I have no clue how to do
    3 weeks 4 days ago
  • well this tutorial is
    4 weeks 4 days ago
  • Exactement, c'est bien pour
    25 weeks 2 days ago
  • Effectivement, ça doit aller
    25 weeks 4 days ago
  • Ou là, t'ai tomber sur quoi
    28 weeks 4 days ago
  • .
    31 weeks 4 days ago
  • Net c'est plus propre :)
    39 weeks 4 days ago
  • Ah ouais pratique... je
    39 weeks 5 days ago
  • Well, if your computer's IP
    42 weeks 1 day ago
  • Hi, have you more information
    42 weeks 1 day ago

Tags

Divers Drupal drupal emacs firefox git gmap Google html validator Images Jquery jquery karmic koala La phrase du jour Lausanne Logiciels libres mysql PHP 5 shell ssh Sys admin ubuntu Web Dev Zend
more tags

Popular content

Today's:

  • RewriteRule mobile
  • [Drupal] Domain Access & memcache sa donne quoi ?
  • Chat webapp with node.js
  • Drupal en Intranet
  • Drupal 7 effet avec les jquery.ui.dialog sur Drupal 6 !
  • Php 5.3 -> php 5.2
  • Emacs and shell
  • Jquery cycle
  • Infomaniak c'est des glands!
  • Hébergeur Gratuit avec Python et Django

All time:

  • Drupal 7 effet avec les jquery.ui.dialog sur Drupal 6 !
  • Chat webapp with node.js
  • [Drupal] Domain Access & memcache sa donne quoi ?
  • Dries Keynote DrupalCon Paris 2009
  • Qu'elle version de drupal utilisez-vous ?
  • Quel framwork php utilisez vous ?
  • Drupal bridge zend yeah !!
  • Jquery slider c'est de la bonne !!!
  • Jquery JSON en _POST
  • Drupal and Zend, form validate :)

Last viewed:

  • Firefox 64 bit
  • www.kursus.ch
  • Décapsuleur heineken inscusté dans le mur
  • Infomaniak c'est des glands!
  • Tinymce styles sorted
  • Squall Beer Challenge '09 - Epic fail !
  • Chat webapp with node.js
  • Exclu : SuisseID and Drupal CMS
  • Drupal zend présentation
  • [Drupal 6] Home Box

Twitter

Latest Articles

Derniers liens publiés

  • Sorry, there have been more than 5 failed login attempts for this account. It is temporarily blocked.
    http://drupal.org/node/1023440
  • Drupal drush slow on postgresql
    http://www.postgresql.org/docs/9.1/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT
  • Sudo sans password dans jenkins
    http://www.zimbra.com/forums/installation/10553-solved-sudo-sorry-you-must-have-tty-run-sudo.html
  • Drupal form submit
    http://significantbits.wordpress.com/2008/05/30/drupal-returning-an-error-and-keeping-field-values-when-form-submit-fails/
  • Drupal 7 WKT to KML
    https://github.com/arenevier/gisconverter.php

Google gadget

Add to Google

Facebook page

Partenaires

Cyber Warfare

Drupal Factory

Dev Factory

I love Smashing Magazine!
Fervens Drupal theme by Leow Kah Thong. Designed by Design Disease and brought to you by Smashing Magazine.