function stopKeepAlive(responseAndIsES) {
if (responseAndIsES.keepAliveTimeout) {
clearTimeout(responseAndIsES.keepAliveTimeout);
+ responseAndIsES.keepAliveTimeout = 0;
}
}
function keepAlive(responseAndIsES) {
stopKeepAlive(responseAndIsES);
- responseAndIsES.keepAliveTimeout = setTimeout(function () {
+ responseAndIsES.keepAliveTimeout = setTimeout(function keepAliveTimeout() {
responseAndIsES[0].write(
responseAndIsES[1]
? ":\n\n"
that.listeningPlayers.push(responseAndIsES);
keepAlive(responseAndIsES);
- responseAndIsES[0].on("close", function () {
+ var closed = false;
+
+ function close () {
+ if (closed) {
+ return;
+ }
+
+ closed = true;
stopKeepAlive(responseAndIsES);
+
var index = that.listeningPlayers.indexOf(responseAndIsES);
if (index !== -1) {
that.listeningPlayers[index] = that.listeningPlayers[that.listeningPlayers.length - 1];
that.listeningPlayers.pop();
}
- });
+ }
+
+ responseAndIsES[0].on("close", close);
+ responseAndIsES[0].on("finish", close);
+ responseAndIsES[0].on("prefinish", close);
this.playerJoined(playerName);
this.commit();
function handleRequest(request, response) {
var post = "";
+ var responseAndIsES = [response, false];
+
+ response.on("error", function (e) {
+ console.error("An error occurred while trying to write on a socket", e);
+ stopKeepAlive(responseAndIsES);
+ });
// Thx http://stackoverflow.com/questions/4295782/how-do-you-extract-post-data-in-node-js
request.on("data", function (data) {
return;
}
- var isEventSource = false;
var eventSourceMatch = request.url.match(/\/:[^/]+\/sse\/(?<data>[\s\S]+)$/u);
if (eventSourceMatch) {
response.setHeader("Content-Type", "text/event-stream");
post = decodeURIComponent(eventSourceMatch.groups.data);
- isEventSource = true;
+ responseAndIsES[1] = true;
} else {
response.setHeader("Content-Type", "text/plain");
response.setHeader("Transfer-Encoding", "chunked");
}
dateNow = Date.now();
- debuglog("RECEIVED", request.url, post, isEventSource);
- handleCommands(post && JSON.parse(post), [response, isEventSource]);
+ debuglog("RECEIVED", request.url, post, responseAndIsES[1]);
+ handleCommands(post && JSON.parse(post), responseAndIsES);
});
}