JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
parse in the client too, limit to 50fps
[watch-my-terminal.git] / server.coffee
1 handler = (req, res) ->
2         reply_err = (req, res, msg) ->
3                 res.writeHead(200, 'Content-Type': 'text/plain')
4                 return res.end("Error loading #{req.url} \"#{msg}\"")
5         switch req.url
6                 when '/', '/index.html'
7                         filename = __dirname + '/index.html'
8                         type = 'text/html'
9                 when '/jquery.js'
10                         filename = '/usr/share/javascript/jquery/jquery.min.js'
11                         type = 'text/javascript'
12                 when '/terminal.js'
13                         filename = __dirname + '/terminal.coffee'
14                         type = 'text/javascript'
15                 else
16                         return reply_err req, res
17         fs.readFile filename, 'utf8', (err, data) ->
18                 return reply_err req, res, err if err
19
20                 if filename.substr(filename.length - 7) is '.coffee'
21                         try
22                                 data = coffee.compile data
23                         catch e
24                                 return reply_err req, res, "server faild to compile #{filename}: #{JSON.stringify(e)}"
25
26                 res.writeHead(200, 'Content-Type': type)
27                 res.end(data)
28
29 coffee = require 'coffee-script'
30 app = require('http').createServer(handler)
31 io = require('socket.io').listen(app)
32 fs = require('fs')
33 terminal = require('./terminal.coffee')
34
35 # SETTINGS
36 app.listen(9293)
37 term = terminal.new(105, 66)
38
39 sockets = []
40
41 io.sockets.on 'connection', (socket) ->
42         sockets.push socket
43         socket.on 'disconnect', ->
44                 for i in [i...sockets.length]
45                         if sockets[i] is socket
46                                 sockets.splice i, 1
47                                 return
48
49         socket.emit 'init', width: term.width, height: term.height, x: term.x, y: term.y, a: term.a, text: term.text, attributes: term.attributes
50
51 process.stdin.resume()
52 process.stdin.setEncoding 'utf8'
53
54 process.stdin.on 'data', (data) ->
55         term.update data
56         for s in sockets
57                 s.emit 'data', data
58
59 process.stdin.on 'end', -> process.exit()