Skip to content

Instantly share code, notes, and snippets.

@sherbondy
Created February 22, 2011 10:24
Show Gist options
  • Save sherbondy/838474 to your computer and use it in GitHub Desktop.
Save sherbondy/838474 to your computer and use it in GitHub Desktop.
The example socket.io server, rewritten in CoffeeScript
http = require 'http'
url = require 'url'
fs = require 'fs'
io = require 'socket.io'
sys = require if process.binding('natives').util then 'util' else 'sys'
server = http.createServer (req, res) ->
path = url.parse(req.url).pathname
switch path
when '/'
res.writeHead 200, {'Content-Type': 'text/html'}
res.write '<h1>Welcome. Try the <a href="/chat.html">chat</a> example.</h1>'
res.end()
when '/json.js', '/chat.html'
fs.readFile __dirname + path, (err, data) ->
if err then send404(res)
res.writeHead 200, {'Content-Type': if path is 'json.js' then 'text/javascript' else 'text/html'}
res.write data, 'utf8'
res.end()
else send404(res)
send404 = (res)->
res.writeHead(404)
res.write('404')
res.end()
server.listen 8080
io = io.listen server
buffer = []
io.on 'connection', (client)->
client.send { buffer: buffer }
client.broadcast { announcement: client.sessionId + ' connected' }
client.on 'message', (message)->
msg = { message: [client.sessionId, message] }
buffer.push msg
if buffer.length > 15 then buffer.shift()
client.broadcast msg
client.on 'disconnect', ()->
client.broadcast { announcement: client.sessionId + ' disconnected' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment