Mar 2, 2014

How to create a simple chat with Node.js, Express and Socket.io

In this post we will learn how to create our first chat, it is very easy. We need to have installed Node.js and Express. If you don't have it, you can see how do it in this post:

Node.js -> How install Node.js?

Express -> First project with Express and Node.js

Now, we are ready to creating our chat.





Create the project

1 - Open your terminal and headed to the directory where we want to create our project

2 - Write in the terminal:    $ express easyChat  

3 - Headed to the project folder and opened the file "package.json" and insert a new line in dependecies:


"dependencies": {
    "express": "3.4.8",
    "jade": "*",
    "socket.io": "*"
  }

this is the module that will allow us to chat communications

4 - choose de folder of the proyect in the terminal:    $  cd easyChat  

5 - install dependencies, write in the terminal:   $ npm install  


Create the server

Open the file "app.js" and change the last line by:


// create the var server 
var server = http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

// create our server socket
var io = require('socket.io').listen(server);

// listen the messages and answer
io.sockets.on('connection',function(socket){

        // listen
socket.on('message',function(data){
             
                        // answer
io.sockets.emit('message', data);

});
});





Create the view

Open the file "views/index.jade" and change the text by:



extends layout

block content
h1 EasyChat
form
input(type="text",id="message")
input(type="submit", value="send!")
div#chat
script(src='http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js')
script(src='/socket.io/socket.io.js')
script(type='text/javascript' src='/javascripts/functions.js')


becareful with the tabulated, jade is very sensitive with them


Create the user's socket

Create a new file in /public/javascripts/ called "functions.js":


// create the user's socket
var socket = io.connect();

jQuery(function ($) {

var formChat = $('#formChat');
var message = $('#message');

         // when push the button "send", the message is sent to the server
          formChat.submit(function(event){

event.preventDefault();
socket.emit('message',message.val());

});
     
        // listen the server and print the message
socket.on('message',function(data){

   $('#chat').prepend('<p> - '+ data +' </p>');
});

});

Now we have our first chat!!!! you can see the demo in the video:




I hope you liked it, and if you have any questions feel free to write me:


No comments:

Post a Comment