Creation of a chat

Part 1  – Hello

  • Install NodeJS LTS 
  • In your project directory, add a package.json file
{
	"name": "Chat",
	"version": "0.0.1",
	"private": true,
	"scripts": {
		"start": "node index.js"
	},
	"dependencies": {
		"express": "4"
	}
}
  • copy the following code in a index.js file
var port = 3000;
var hostname = 'localhost'
var express = require('express');
var http = require('http');
var app = express(); 
var server = http.createServer(app);

app.get('/', function(req, res){
  res.send('Hello world');
});
server.listen(port,hostname, function(){ 
  console.log("Mon serveur fonctionne sur http://"+ hostname +":"+port); 
});
  • run
npm install
npm start
  • test the display using the browser navigateur http://localhost:3000

 

Part 2 – HTML file

  • change the url / call to allow the display of an HTML file
app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});
  • add the index.html file
<!doctype html>
<html>
  <head>
    <title>Chat NodeJs</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 85%; margin-right: .5%; }
      form button { width: 14%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Envoyer</button>
    </form>
  </body>
</html>
  • test the display

 

Part 3 – Receive events

  • run
npm install socket.io
  • modify the index.js file
var port = 3000;
var hostname = 'localhost'
var express = require('express');
var http = require('http');
var app = express(); 
var server = http.createServer(app);
var io = require('socket.io')(server);



app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
  console.log('un utilisateur est connecté');
socket.on('disconnect', function(){
    console.log('utilisateur déconnecté');
  });
});
server.listen(port,hostname, function(){ 
  console.log("Mon serveur fonctionne sur http://"+ hostname +":"+port); 
});
  • add this code before <body>
<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io();
</script>
  • test your page and look at the server console
  • refresh the page and look at the console

 

Part 4 – Retrieve the message

  • modify index.html
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
  $(function () {
    var socket = io();
    $('form').submit(function(e){
      e.preventDefault(); // prevents page reloading
      socket.emit('chat message', $('#m').val());
      $('#m').val('');
      return false;
    });    
  });
</script>

 

  • in index.js modify io.on with
io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
  socket.on('chat message', function(msg){
    console.log('message: ' + msg);
  });
});
  • test your page and look at the server console

 

 

Part 5 – Send to all

  • modify index.js
socket.on('chat message', function(msg){
   console.log('message: ' + msg);    
   io.emit('chat message', msg);
  });
  • modify index.html
<script>
  $(function () {
    var socket = io();
    $('form').submit(function(e){
      e.preventDefault(); // prevents page reloading
      socket.emit('chat message', $('#m').val());
      $('#m').val('');
      return false;
    });
    socket.on('chat message', function(msg){
      $('#messages').append($('<li>').text(msg));
    });
  });
</script>
  • test the chat with 2 pages.

 

Part 6

  • Add the users’ names (socket.emit and socket.on)
  • Inform the users that somebody disconnected (socket.emit)
  • See who is writing
  • See who is online