Skip to content

Commit

Permalink
send filler packets to keep latency low
Browse files Browse the repository at this point in the history
  • Loading branch information
valsteen committed Oct 12, 2015
1 parent 096adf6 commit 43551ef
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 5 deletions.
39 changes: 38 additions & 1 deletion node_app/server.js
Expand Up @@ -34,6 +34,42 @@ var io = require('socket.io')(server);


io.on('connection', function (socket) {
var done = false;
var fillerTimeout = null;

socket.on("disconnect", function () {
done = true;
if (fillerTimeout) {
clearTimeout(fillerTimeout);
}
});

function sendFiller() {
if (!done) {
socket.send("filler");
if (Date.now() - socket.conn.lastMidi < 1000) {
fillerTimeout = setTimeout(sendFiller, 50);
}
}
}

socket.conn.startFiller = function () {
socket.conn.lastMidi = Date.now();
if (!fillerTimeout) {
fillerTimeout = setTimeout(sendFiller, 50);
}
};

socket.conn.on('packetCreate', function (d) {
if (d.data !== '2["message","filler"]') {
// we're already sending a packet, so cancel next filler
if (fillerTimeout) {
clearTimeout(fillerTimeout);
fillerTimeout = setTimeout(sendFiller, 50);
}
}
});

socket.on('message', function (data) {
midi.sendMidi([240, 247]);
zmq.request(data).then(
Expand All @@ -53,9 +89,10 @@ var iomidi = io.of("/midi");

iomidi.on('connection', function (socket) {
socket.on('message', function (data) {
socket.conn.startFiller();
socket.send("ack"); // this trick should prevent nagle's algorithm. Some serious profiling is needed to be sure http://stackoverflow.com/a/13406438/34871
if (!data.notes && data.constructor !== Array) { // tried to send filler packets to force flushing, so data.notes will be not present for them
return ;
return;
}

var notes;
Expand Down
7 changes: 3 additions & 4 deletions src/io.js
@@ -1,8 +1,7 @@
import io from 'socket.io-client';

var url = window.location.protocol + "//" + window.location.host + "/";
var opts = {transports: ["websocket"]};

export var iorequest = io(url, opts);
export var ioevents = io(url + 'events', opts);
export var iomidi = io(url + 'midi', {transports: ["websocket"], forceNew: true});
export var iorequest = io(url);
export var ioevents = io(url + 'events');
export var iomidi = io(url + 'midi');

0 comments on commit 43551ef

Please sign in to comment.