Permalink
Browse files

node files, some weird host code in there

  • Loading branch information...
Adrian Seeley
Adrian Seeley committed Jun 15, 2015
1 parent e89b39a commit 41b1d85ed0c9187ee89467c8b3d5c2591d1ff010
Showing with 97 additions and 0 deletions.
  1. +27 −0 .gitignore
  2. +10 −0 index.js
  3. +60 −0 lockstepio.js
View
@@ -0,0 +1,27 @@
# Logs
logs
*.log
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directory
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
node_modules
View
@@ -0,0 +1,10 @@
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var lockstepio = require('./lockstepio.js')(io);
app.listen(80);
function handler (req, res) {
res.writeHead(200);
res.end('oh hey');
};
View
@@ -0,0 +1,60 @@
module.exports = function (io) {
var ref = {
io: io,
commandDelay: 30,
sockets: {},
stateSync: {},
randomSeed: parseInt(Math.random() * 10000),
onConnection: function (socket) {
// if we have no host make host
if (!ref.host) {
socket.is_host = true;
ref.host = socket.id;
}
ref.sockets[socket.id] = {socket: socket};
socket.on('disconnect', function() {
if (ref.host == socket.id) {
delete ref['host'];
}
delete ref.sockets[socket.id];
});
socket.emit('lockstepio:seed', {randomSeed: ref.randomSeed});
socket.on('lockstepio:sync', function (ntp) {
if (socket.is_host) {
socket.emit('lockstepio:sync', {t0: ntp.t0, t1: ntp.t0});
} else {
socket.emit('lockstepio:sync', {t0: ntp.t0, t1: ref.sockets[ref.host].sync.localNow});
}
});
socket.on('lockstepio:ready', function (ready) {
ref.sockets[socket.id].sync = ready;
var clients = {};
for (var id in ref.sockets) {
clients[id] = ref.sockets[id].sync;
}
var pkg = {commandDelay: ref.commandDelay, clients: clients};
ref.io.emit('lockstepio:ready', pkg);
});
socket.on('lockstepio:cmd:issue', function (command) {
// if this command is a state sync (ENUM 0, stateSync)
if (command.dispatcher == 0) {
if (!ref.stateSync.hasOwnProperty(command.lockstepTime)) {
ref.stateSync[command.lockstepTime] = {};
}
ref.stateSync[command.lockstepTime][socket.id] = command.hash;
if (socket.is_host && command.lockstepTime % 30 == 0) {
console.log(ref.stateSync[command.lockstepTime]);
}
return; // return out for now, don't relay sync
}
ref.io.emit('lockstepio:cmd:issue', command);
});
},
issueCommand: function (command) {
command.atLockstep = new Date().getTime() + ref.commandDelay;
ref.io.emit('lockstepio:cmd:issue', command);
}
};
ref.io.on('connection', ref.onConnection);
return ref;
};

0 comments on commit 41b1d85

Please sign in to comment.