44 lines
1.3 KiB
CoffeeScript
44 lines
1.3 KiB
CoffeeScript
fs = require "fs"
|
|
express = require "express"
|
|
app = express()
|
|
expressWs = require("express-ws")(app)
|
|
sockets = []
|
|
|
|
try
|
|
config = require("./config.js")
|
|
catch error
|
|
console.log "cannot find config, auto-creating"
|
|
sampleConfig = "var config = {};\nconfig.port = 3000;\nmodule.exports = config;\n"
|
|
fs.writeFileSync "./config.js", sampleConfig
|
|
config = {port: 3000}
|
|
# the counter itself
|
|
counter = 0
|
|
|
|
app.use express.static("static")
|
|
|
|
removeElement = (array, elem) ->
|
|
index = array.indexOf(elem)
|
|
array.splice(index, 1) if index > -1
|
|
|
|
broadcastCounter = ->
|
|
sockets.forEach (socket) ->
|
|
socket.send counter
|
|
|
|
app.ws "/api", (ws, req) ->
|
|
ws.send counter
|
|
sockets.push ws
|
|
ws.on "message", (msg) ->
|
|
switch
|
|
when msg=="inc"
|
|
counter = counter + 1
|
|
when msg=="dec"
|
|
counter = counter - 1
|
|
else
|
|
errored = true
|
|
ws.send "err"
|
|
broadcastCounter() if not errored
|
|
ws.on "close", -> removeElement sockets, ws
|
|
|
|
app.listen config.port, () ->
|
|
console.log("ready on port " + config.port)
|