Advertisement
Guest User

Untitled

a guest
Jul 8th, 2014
297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  * APP.JS
  3.  *
  4.  * Notice that AppFog passes the listen port for your app in an environment variable,
  5.  * accessed by process.env.VCAP_APP_PORT
  6.  *
  7.  *
  8. */
  9.  
  10. //REQUIREMENTS
  11. var
  12.    express = require("express"),
  13.    logger = require("morgan"),
  14.    WebSocketServer = require("ws").Server;
  15.  
  16. //MASTER VARIABLE DEFINITIONS
  17. var
  18.    httpPort = process.env.PORT || 3000,
  19.    wsPort = 3001,
  20.    wss = new WebSocketServer({port:wsPort}),
  21.    wsgrid = {},
  22.    app = express();
  23.  
  24. //SHORT FUNCTION DEFINITIONS
  25. var
  26.    //Handle incoming messages from clients
  27.    wsHandleMessage = function(rawMessage) {
  28.       var
  29.          messageArray = rawMessage.split(":"),
  30.          messageType = messageArray[0],
  31.          message = messageArray[1];
  32.  
  33.       switch(messageType){
  34.          case "broadcast":
  35.             var originClientID = messageArray[2];
  36.             for(var wsid in wsgrid){ //broadcast to every client
  37.                safeSend(wsid,rawMessage);
  38.             }
  39.          break;
  40.       }
  41.    },
  42.  
  43.    //Safely send a message to a client
  44.    safeSend = function(wsid,msg){
  45.       var ts = new Date().getTime();
  46.       console.log(ts,wsid,msg);
  47.       if(wsgrid[wsid].readyState == wsgrid[wsid].OPEN){ wsgrid[wsid].send(msg); }
  48.    },
  49.  
  50.    //Safely close a client websocket connection
  51.    closeSocket = function(wsid){delete wsgrid[wsid];},
  52.  
  53.    //Generate a unique client handle
  54.    generateUIDNotMoreThan1million = function() { return ("0000" + (Math.random()*Math.pow(36,4) << 0).toString(36)).slice(-4); },
  55.  
  56.    //create the heartbeat function with access to local variables
  57.    hb = function(wsid){
  58.       if(wsgrid[wsid].readyState != wsgrid[wsid].OPEN){
  59.          closeSocket(wsid);
  60.          console.log("WS "+wsid+" has disconnected.");
  61.          return;
  62.       }
  63.       safeSend(wsid,"hb");
  64.       setTimeout(function(){hb(wsid);},5000);
  65.    };
  66.  
  67. //LISEN UP SERVER!
  68.  
  69. //Create a websocket server
  70. wss.on('connection', function(ws) {
  71.    var wsid = generateUIDNotMoreThan1million(); //my own custom hack to the ws object to give it an easily accessible id
  72.    wsgrid[wsid] = ws;
  73.    wsgrid[wsid].on('message', wsHandleMessage);
  74.    safeSend(wsid,"connected:"+wsid);
  75.    hb(wsid); //start the heartbeat
  76. });
  77.  
  78. //HTTP Server Middleware
  79. app.get("/", function(req, res) {res.sendfile("index.html");});
  80. app.get("/*", function(req, res) {res.sendfile("script.js");});
  81.  
  82. //HTTP Server
  83. app.listen(httpPort);
  84.  
  85. console.log("Server running.");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement