- // TODO: later, allow duplicate connections (shouldn't be much more complicated)
- // Ignore duplicate connections (on the same live game that we play):
- if (!!clients[sid])
- return socket.send(JSON.stringify({code:"duplicate"}));
- clients[sid] = socket;
- // Notify room:
- Object.keys(clients).forEach(k => {
- if (k != sid)
- clients[k].send(JSON.stringify({code:"connect",sid:sid}));
- });
- socket.on("message", objtxt => {
+ const id = query["id"];
+ const tmpId = query["tmpId"];
+ const page = query["page"];
+ const notifyRoom = (page, code, obj={}, except) => {
+ if (!clients[page]) return;
+ except = except || [];
+ Object.keys(clients[page]).forEach(k => {
+ if (except.includes(k)) return;
+ Object.keys(clients[page][k]).forEach(x => {
+ if (k == sid && x == tmpId) return;
+ send(
+ clients[page][k][x].socket,
+ Object.assign({ code: code, from: [sid, tmpId] }, obj)
+ );
+ });
+ });
+ };
+ const deleteConnexion = () => {
+ if (!clients[page] || !clients[page][sid] || !clients[page][sid][tmpId])
+ return; //job already done
+ delete clients[page][sid][tmpId];
+ if (Object.keys(clients[page][sid]).length == 0) {
+ delete clients[page][sid];
+ const pgIndex = sidToPages[sid].findIndex(pg => pg == page);
+ sidToPages[sid].splice(pgIndex, 1);
+ if (Object.keys(clients[page]).length == 0)
+ delete clients[page];
+ // Am I totally offline?
+ if (sidToPages[sid].length == 0) {
+ delete sidToPages[sid];
+ delete idToSid[id];
+ }
+ }
+ };
+
+ const doDisconnect = () => {
+ deleteConnexion();
+ // Nothing to notify when disconnecting from MyGames page:
+ if (page != "/mygames") {
+ notifyRoom(page, "disconnect");
+ if (page.indexOf("/game/") >= 0)
+ notifyRoom("/", "gdisconnect", { page: page });
+ }
+ };
+ const messageListener = (objtxt) => {