- let clients = {}; //associative array sid --> socket
- wss.on("connection", (socket, req) => {
- const query = getJsonFromUrl(req.url);
- const sid = query["sid"];
- // 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 => {
- let obj = JSON.parse(objtxt);
- if (!!obj.target && !clients[obj.target])
- return; //receiver not connected, nothing we can do
- //console.log(obj.code);
- switch (obj.code)
- {
- case "pollclients":
- socket.send(JSON.stringify({code:"pollclients",
- sockIds:Object.keys(clients).filter(k => k != sid)}));
- break;
- case "askidentity":
- clients[obj.target].send(
- JSON.stringify({code:"askidentity",from:sid}));
+ // Associative array page --> sid --> tmpId --> socket
+ // "page" is either "/" for hall or "/game/some_gid" for Game,
+ // tmpId is required if a same user (browser) has different tabs
+ let clients = {};
+ wss.on("connection", (socket, req) => {
+ const query = getJsonFromUrl(req.url);
+ const sid = query["sid"];
+ const tmpId = query["tmpId"];
+ const page = query["page"];
+ const notifyRoom = (page,code,obj={}) => {
+ if (!clients[page])
+ return;
+ Object.keys(clients[page]).forEach(k => {
+ Object.keys(clients[page][k]).forEach(x => {
+ if (k == sid && x == tmpId)
+ return;
+ send(clients[page][k][x], Object.assign({code:code, from:sid}, 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];
+ if (Object.keys(clients[page]) == 0)
+ delete clients[page];
+ }
+ };
+ const doDisconnect = () => {
+ deleteConnexion();
+ if (!clients[page] || !clients[page][sid])
+ {
+ // I effectively disconnected from this page:
+ notifyRoom(page, "disconnect");
+ if (page.indexOf("/game/") >= 0)
+ notifyRoom("/", "gdisconnect", {page:page});
+ }
+ };
+ const messageListener = (objtxt) => {
+ let obj = JSON.parse(objtxt);
+ switch (obj.code)
+ {
+ // Wait for "connect" message to notify connection to the room,
+ // because if game loading is slow the message listener might
+ // not be ready too early.
+ case "connect":
+ {
+ notifyRoom(page, "connect");
+ if (page.indexOf("/game/") >= 0)
+ notifyRoom("/", "gconnect", {page:page});