-
Notifications
You must be signed in to change notification settings - Fork 1
/
dropletServer.js
65 lines (51 loc) · 1.33 KB
/
dropletServer.js
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
"use strict";
var st = require("st")
, http = require("http")
, shoe = require('shoe')
, MODE = process.argv[2]
, PORT
if (MODE == "-p")
PORT = 80
else if (MODE == "-d")
PORT = 8080
else {
console.log("Unknown flag, use -p for production or -d for development")
process.exit()
}
var server = http.createServer( serverHandler )
server.listen(PORT, function() {
console.log("Listening on port " + PORT)
})
var sock = shoe(socketHandler)
sock.install(server, "/droplets")
var cstreams = {}
server.on('connection', function (socket) {
var id = socket.remoteAddress + socket.remotePort
socket.on('close', removeID(id))
})
var staticOptions = {
path: './public/'
, url: '/'
, index: 'index.html' // use 'index.html' file as the index
, dot: false // default: return 403 for any url with a dot-file part
, passthrough: false // calls next instead of returning a 404 error
}
var mount = st(staticOptions)
function serverHandler(req, res) {
return mount(req, res)
}
function socketHandler (stream) {
var id = stream.remoteAddress + stream.remotePort
cstreams[id] = stream
stream.on('data', function (packet) {
Object.keys(cstreams).forEach( function (key) {
if (key !== id) cstreams[key].write(packet)
return
})
})
}
function removeID (id) {
return function (socket) {
delete cstreams[id]
}
}