forked from jamesshore/lets_code_javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
59 lines (46 loc) · 1.7 KB
/
server.js
File metadata and controls
59 lines (46 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Copyright (c) 2012 Titanium I.T. LLC. All rights reserved. See LICENSE.txt for details.
(function() {
"use strict";
var http = require("http");
var fs = require("fs");
var send = require("send");
var io = require('socket.io');
var Server = module.exports = function Server() {};
Server.prototype.start = function(contentDir, notFoundPageToServe, portNumber, callback) {
if (!portNumber) throw "port number is required";
this._httpServer = http.createServer();
handleHttpRequests(this._httpServer, contentDir, notFoundPageToServe);
this._ioServer = io(this._httpServer);
handleSocketIoEvents(this._ioServer);
this._httpServer.listen(portNumber, callback);
};
Server.prototype.stop = function(callback) {
if (this._httpServer === undefined) return callback(new Error("stop() called before server started"));
this._httpServer.close(callback);
};
function handleHttpRequests(httpServer, contentDir, notFoundPageToServe) {
httpServer.on("request", function(request, response) {
send(request, request.url, { root: contentDir }).on("error", handleError).pipe(response);
function handleError(err) {
if (err.status === 404) serveErrorFile(response, 404, contentDir + "/" + notFoundPageToServe);
else throw err;
}
});
}
function handleSocketIoEvents(ioServer) {
ioServer.on("connect", function(socket) {
socket.on("mouse", function(data) {
console.log(data);
socket.broadcast.emit("mouse", data);
});
});
}
function serveErrorFile(response, statusCode, file) {
response.statusCode = statusCode;
response.setHeader("Content-Type", "text/html; charset=UTF-8");
fs.readFile(file, function(err, data) {
if (err) throw err;
response.end(data);
});
}
}());