-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
executable file
·78 lines (65 loc) · 2.28 KB
/
server.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
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env node
var EventEmitter = require('events').EventEmitter
, chalk = require('chalk')
, mdns = require('mdns')
, networkAddress = require('network-address')
, tomatoLength = 25 * 60
, pauseLength = 5 * 60
, emitter = new EventEmitter()
, work = function () {
var start = Date.now()
, interval = setInterval(
function () {
var countdown = tomatoLength - Math.round((Date.now() - start) / 1000)
emitter.emit('work', countdown)
if (countdown <= 0) {
clearInterval(interval)
pause()
}
}
, 1000
)
}
, pause = function (callback) {
var start = Date.now()
, interval = setInterval(
function () {
var countdown = pauseLength - Math.round((Date.now() - start) / 1000)
emitter.emit('pause', countdown)
if (countdown <= 0) {
clearInterval(interval)
work()
}
}
, 1000
)
}
, server
emitter.setMaxListeners(Infinity)
server = require('net').createServer(function (connection) {
var remoteAddress = connection.remoteAddress
, onTomato = function (countdown) {
connection.write(JSON.stringify({ type: 'work', countdown: countdown }) + '\n')
}
, onPause = function (countdown) {
connection.write(JSON.stringify({ type: 'pause', countdown: countdown }) + '\n')
}
, cleanup = function () {
console.log(chalk.red('Client disconnected ' + remoteAddress))
emitter.removeListener('work', onTomato)
emitter.removeListener('pause', onPause)
connection.removeListener('end', cleanup)
connection.removeListener('error', cleanup)
}
console.log(chalk.green('Client connected ' + remoteAddress))
emitter.on('work', onTomato)
emitter.on('pause', onPause)
connection.once('end', cleanup)
connection.once('error', cleanup)
}).listen(function () {
var ad = mdns.createAdvertisement(mdns.tcp('tomatotomato'), server.address().port)
, msg = 'server running on ' + networkAddress() + ':' + server.address().port
console.log(chalk.blue(msg))
ad.start()
})
work()