forked from remy/html5demos
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom-echo.js
More file actions
99 lines (80 loc) · 2.51 KB
/
custom-echo.js
File metadata and controls
99 lines (80 loc) · 2.51 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// slightly modified version of echo-server.js for the web-sockets demo
var sys = require("sys")
, fs = require("fs")
, path = require("path")
, http = require("http")
, ws = require(__dirname + '/node-websocket-server/lib/ws');
/*-----------------------------------------------
logging:
-----------------------------------------------*/
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
function timestamp() {
var d = new Date();
return [
d.getDate(),
months[d.getMonth()],
[ pad(d.getHours())
, pad(d.getMinutes())
, pad(d.getSeconds())
, (d.getTime() + "").substr( - 4, 4)
].join(':')
].join(' ');
};
function log(msg) {
sys.puts(timestamp() + ' - ' + msg.toString());
};
function serveFile(req, res){
if( req.url.indexOf("favicon") > -1 ){
log("HTTP: inbound request, served nothing, (favicon)");
res.writeHead(200, {'Content-Type': 'image/x-icon'});
res.end("");
} else {
log("HTTP: inbound request, served client.html");
res.writeHead(200, {'Content-Type': 'text/html'});
fs.createReadStream( path.normalize(path.join(__dirname, "client.html")), {
'flags': 'r',
'encoding': 'binary',
'mode': 0666,
'bufferSize': 4 * 1024
}).addListener("data", function(chunk){
res.write(chunk, 'binary');
}).addListener("close",function() {
res.end();
});
}
};
/*-----------------------------------------------
Spin up our server:
-----------------------------------------------*/
var httpServer = http.createServer(serveFile);
var connected = 0;
var server = ws.createServer({
debug: true
}, httpServer);
server.addListener("listening", function(){
log("Listening for connections on " + process.ARGV[2]);
});
// Handle WebSocket Requests
server.addListener("connection", function(conn){
log("opened connection: "+conn.id);
connected++;
server.send(conn.id, connected+'');
conn.broadcast(connected+'');
conn.addListener("message", function(message){
log("<"+conn.id+"> "+message);
conn.broadcast(message);
});
});
server.addListener("close", function(conn){
log("closed connection: "+conn.id);
connected--;
conn.broadcast(connected+'');
});
server.listen(parseInt(process.ARGV[2]) || 8000);
// Handle HTTP Requests:
// This will hijack the http server, if the httpserver doesn't
// already respond to http.Server#request
// server.addListener("request", serveFile);