Commits

Linh Tran committed 6d809ba

Initial Upload

Comments (0)

Files changed (1)

+var net = require('net'),
+    carrier = require('carrier');
+
+// Client class to hold player name and connection
+function Client(connection) {
+    this.name = null;
+    this.online_id = null;
+    this.connection = connection;
+}
+
+// Array to hold list of connected client
+var clients = [];
+
+// Define tcp server for the game
+var tcp_server = net.createServer(function(conn) {
+    console.log('Server connected');
+    
+    var client = new Client(conn);
+    clients.push(client);
+    
+    conn.setTimeout(0);
+    conn.setEncoding('utf8');
+    
+    conn.on('connect', function() {
+        console.log('Client connected');
+        clients.forEach(function(one_client) {
+            if (client !== one_client) {
+                if (one_client.connection !== null) {
+                    one_client.connection.write("new\n");
+                }
+            }
+        });
+    });
+    
+    carrier.carry(conn, function(line) {
+        if (client.name === null) {
+            line_arr = line.split(";");
+            client.name = line_arr[0];
+            client.online_id = line_arr[1];
+            console.log('New client name: ' + client.name);
+            conn.write("connected\n");
+        }
+    });
+});
+
+tcp_server.listen(8088);
+
+//--------- HTTP server part
+var http = require('http'),
+    journey = require('journey'),
+    winston = require('winston');
+
+// Create router function to return the list of all players
+var createRouter = function() {
+    var router = new (journey.Router)();
+    
+    router.path('/players', function() {
+        this.get().bind(function(req, res) {
+            // Get the name of all connected players
+            var players = clients.map(function(client) {
+                return { name: client.name, id: client.online_id };
+            });
+            res.send(200, {}, { players: players });
+        });
+    });
+    
+    return router;
+};
+
+// HTTP server to return list of all players
+var http_serv = http.createServer(function(req, res) {
+    var body = '';
+    var router = createRouter();
+    
+    winston.info('Incoming Request', { url: req.url });
+        
+    req.on('data', function(chunk) {
+        body += chunk;
+    });
+        
+    req.on('end', function() {
+        // Dispatch the request to the service
+        var emitter = router.handle(req, body, function(result) {
+            res.writeHead(result.status, result.headers);
+            res.end(result.body);
+        });
+        
+        emitter.on('log', function(info) {
+            winston.info('Request completed', info);
+        });
+    });
+});
+
+http_serv.listen(9099);