Guest User

chat-server.js

a guest
Sep 6th, 2018
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. "use strict";
  2.  
  3. // Optional. You will see this name in eg. 'ps' or 'top' command
  4. process.title = 'node-chat';
  5.  
  6. // Port where we'll run the websocket server
  7. const webSocketsServerPort = 1337;
  8.  
  9. // websocket and http servers
  10. const webSocketServer = require('websocket').server;
  11. const http = require('http');
  12. const fs = require('fs');
  13. const path = require('path');
  14.  
  15. /**
  16.  * Global variables
  17.  */
  18. // latest 100 messages
  19. var history = [ ];
  20. // list of currently connected clients (users)
  21. var clients = [ ];
  22.  
  23. /**
  24.  * Helper function for escaping input strings
  25.  */
  26. function htmlEntities(str) {
  27.     return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;')
  28.                       .replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  29. }
  30.  
  31. function shuffle(array) {
  32.     let counter = array.length;
  33.  
  34.     while (counter > 0) {
  35.         const index = Math.floor(Math.random() * counter);
  36.         counter--;
  37.         const temp = array[counter];
  38.         array[counter] = array[index];
  39.         array[index] = temp;
  40.     }
  41.  
  42.     return array;
  43. }
  44.  
  45. // Array with some colors
  46. var colors = shuffle([ 'red', 'green', 'blue', 'magenta', 'purple', 'plum', 'orange' ]);
  47.  
  48. /**
  49.  * HTTP server
  50.  */
  51. var server = http.createServer(function(request, response) {
  52.     // Only support two things, send frontend.html and chat-frontend.js
  53.     let filePath = '.' + request.url;
  54.     if (filePath == './') {
  55.         filePath = './frontend.html';
  56.     }
  57.  
  58.     let contentType = 'text/html';
  59.     if (path.extname(filePath) == '.js') {
  60.         contentType = 'text/javascript';
  61.     }
  62.  
  63.     fs.readFile(filePath, function(error, content) {
  64.         response.writeHead(200, { 'Content-Type' : contentType });
  65.         response.end(content, 'utf-8');
  66.     });
  67. });
  68.  
  69. server.listen(webSocketsServerPort, function() {
  70.     console.log((new Date()) + " Server is listening on port " + webSocketsServerPort);
  71. });
  72.  
  73. /**
  74.  * WebSocket server
  75.  */
  76. const wsServer = new webSocketServer({
  77.     // WebSocket server is tied to a HTTP server. WebSocket request is just
  78.     // an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6
  79.     httpServer: server
  80. });
  81.  
  82. // This callback function is called every time someone
  83. // tries to connect to the WebSocket server
  84. wsServer.on('request', function(request) {
  85.     console.log((new Date()) + ' Connection from origin ' + request.origin + '.');
  86.  
  87.     // accept connection - you should check 'request.origin' to make sure that
  88.     // client is connecting from your website
  89.     // (http://en.wikipedia.org/wiki/Same_origin_policy)
  90.     const connection = request.accept(null, request.origin);
  91.     // we need to know client index to remove them on 'close' event
  92.     const index = clients.push(connection) - 1;
  93.     let userName = false;
  94.     let userColor = false;
  95.  
  96.     console.log((new Date()) + ' Connection accepted.');
  97.  
  98.     // send back chat history
  99.     if (history.length > 0) {
  100.         connection.sendUTF(JSON.stringify( { type: 'history', data: history} ));
  101.     }
  102.  
  103.     // user sent some message
  104.     connection.on('message', function(message) {
  105.         if (message.type === 'utf8') { // accept only text
  106.             if (userName === false) { // first message sent by user is their name
  107.                 // remember user name
  108.                 userName = htmlEntities(message.utf8Data);
  109.                 // get random color and send it back to the user
  110.                 userColor = colors.shift();
  111.                 connection.sendUTF(JSON.stringify({ type:'color', data: userColor }));
  112.                 console.log((new Date()) + ' User is known as: ' + userName
  113.                             + ' with ' + userColor + ' color.');
  114.  
  115.             } else { // log and broadcast the message
  116.                 console.log((new Date()) + ' Received Message from '
  117.                             + userName + ': ' + message.utf8Data);
  118.  
  119.                 send_msg(message, userName, userColor);
  120.             }
  121.         }
  122.     });
  123.  
  124.     // user disconnected
  125.     connection.on('close', function(connection) {
  126.         if (userName !== false && userColor !== false) {
  127.             console.log((new Date()) + " Peer "
  128.                 + connection.remoteAddress + " disconnected.");
  129.             // remove user from the list of connected clients
  130.             clients.splice(index, 1);
  131.             // push back user's color to be reused by another user
  132.             colors.push(userColor);
  133.             send_msg({ utf8Data: "*** disconnected from server ***" }, userName, userColor)
  134.         }
  135.     });
  136.  
  137. });
  138.  
  139. function send_msg(message, userName, userColor) {
  140.     const obj = {
  141.         time: (new Date()).getTime(),
  142.         text: htmlEntities(message.utf8Data),
  143.         author: userName,
  144.         color: userColor
  145.     };
  146.     // we want to keep history of all sent messages
  147.     history.push(obj);
  148.     history = history.slice(-100);
  149.     // broadcast message to all connected clients
  150.     const json = JSON.stringify({ type: 'message', data: obj });
  151.     for (var i = 0; i < clients.length; i++) {
  152.         clients[i].sendUTF(json);
  153.     }
  154. }
Advertisement
Add Comment
Please, Sign In to add comment