La création d’un tchat instantané en utilisant Socket.io et nodeJS

La création d’un tchat instantané en utilisant Socket.io et nodeJS

Etape 1 :

Installation du express.js

Etape 2 :

Installation du Socket.io

npm install socket.io

 

Etape 3 :

La création du notre fichier server.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 8080;

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  socket.on('tchat', function(msg){
    io.emit('tchat', msg);
  });
});

http.listen(port);

 

Etape 4 :

Le contenu du fichier index.html

<!doctype html>
<html>
  <head>
    <title>Tchat en ligne</title>
    <style type="text/css">
      * { 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: 90%; margin-right: .5%; }
      form button { width: 9%; background: #333;cursor:pointer; color:#fff; padding: 10px; }
      #kadri { list-style-type: none; margin: 0; padding: 0; }
      #kadri li { padding: 5px 10px; }
      #kadri { margin-bottom: 40px }
    </style>
  </head>
  <body>
    <ul id="kadri"></ul>
    <form action="" method="">
      <input id="message" autocomplete="off" /><button>Envoyer</button>
    </form>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      $(function () {
        var socket = io();
        $('form').submit(function(){
          socket.emit('tchat', $('#message').val());
          $('#message').val('');
          return false;
        });
        socket.on('tchat', function(msg){
          $('#kadri').append($('<li>').text(msg));
          window.scrollTo(0, document.body.scrollHeight);
        });
      });
    </script>
  </body>
</html>

 

Pour exécuter notre script

node server.js