Created
July 3, 2013 20:45
-
-
Save mb-dev/5922652 to your computer and use it in GitHub Desktop.
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 app = require('http').createServer(handler) | |
, io = require('socket.io').listen(app) | |
, fs = require('fs') | |
var config = require('./settings.js') | |
app.listen(config.port); | |
function handler (req, res) { | |
fs.readFile(__dirname + '/index.html', | |
function (err, data) { | |
if (err) { | |
res.writeHead(500); | |
return res.end('Error loading index.html'); | |
} | |
res.writeHead(200); | |
res.end(data); | |
}); | |
} | |
var user_sockets = {} | |
function sendTo(userName, message, data) { | |
console.log('sending to: ' + userName) | |
console.log(user_sockets) | |
for (var i=0; i < user_sockets[userName].length; i++) { | |
var socket = io.sockets.socket(user_sockets[userName][i]); | |
if(socket) { | |
socket.emit(message, data); | |
} | |
} | |
} | |
io.sockets.on('connection', function (socket) { | |
socket.on('set name', function(data) { | |
if(!user_sockets[data.name]) { | |
user_sockets[data.name] = []; | |
} | |
user_sockets[data.name].push(socket.id); | |
}); | |
socket.on('start edit', function (data) { | |
socket.broadcast.emit('started edit', data); | |
}); | |
socket.on('request edit', function (data) { | |
sendTo(data.currently_editing_user, 'request edit', data); | |
}); | |
socket.on('edit request response pending', function(data) { | |
sendTo(data.requester_user, 'edit request response pending', data); | |
}); | |
socket.on('edit request response', function(data) { | |
sendTo(data.requester_user, 'edit request response', data); | |
sendTo(data.currently_editing_user, 'edit response sent on another window', data); | |
}); | |
socket.on('disconnect', function () { | |
for(var name in user_sockets) { | |
var currentLength = user_sockets.length; | |
while(currentLength--) { | |
if(user_sockets[name][currentLength] === socket.id) { | |
user_sockets[name].splice(currentLength, 1); | |
} | |
} | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment