codingOL

a websocket server implementation NOT in fleck

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