Created
January 21, 2011 09:16
-
-
Save zh/789455 to your computer and use it in GitHub Desktop.
Socket.IO example chat, converted to CoffeeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
http = require('http') | |
url = require('url') | |
fs = require('fs') | |
io = require('../') | |
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) -> | |
return send404 res if err | |
res.writeHead 200, | |
'Content-Type': if path == '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 | |
buffer.shift() if buffer.length > 15 | |
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