Created
June 5, 2011 17:13
-
-
Save clauswitt/1009177 to your computer and use it in GitHub Desktop.
A demo server showing express and socket.io
This file contains hidden or 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
| var express = require('express'), | |
| app = express.createServer(), | |
| io = require('socket.io'); | |
| app.configure(function(){ | |
| app.use(express.methodOverride()); | |
| app.use(express.bodyParser()); | |
| app.use(app.router); | |
| app.use(express.static(__dirname + '/../Public')); | |
| app.use(express.errorHandler()); | |
| app.use(express.logger()); | |
| }); | |
| //A simple action to set the counter | |
| app.get('/sentCounter/set/:count', function(req, res){ | |
| sentCounter = req.params.count; | |
| res.send('ok'); | |
| }); | |
| //A simple action to get the current counter value | |
| app.get('/sentCounter/get', function(req, res){ | |
| res.send('sentCounter: ' + sentCounter); | |
| }); | |
| //A simple action to broadcast a message to all connected users. | |
| app.get('/message/broadcast/:msg', function(req, res){ | |
| socket.broadcast({sentCounter: sentCounter, message: req.params.msg}); | |
| res.send('ok'); | |
| }); | |
| app.listen(9099); | |
| var sentCounter = 0; | |
| var socket = io.listen(app); | |
| socket.on('connection', function(client){ | |
| socket.broadcast({sentCounter: sentCounter, message: 'Another client connected'}); | |
| client.on('message', function(data){ | |
| sentCounter++; | |
| socket.broadcast({sentCounter: sentCounter, message: data}); | |
| }); | |
| client.on('disconnect', function(){ | |
| socket.broadcast({sentCounter: sentCounter, message: 'Another client disconnected'}); | |
| }); | |
| }); | |
| var sender = function() { | |
| sentCounter++; | |
| socket.broadcast({sentCounter:sentCounter, message: 'This is an auto message - msg #'+sentCounter}); | |
| //Call myself again in 20 seconds | |
| setTimeout(sender, 20000); | |
| } | |
| sender(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment