1 const url
= require('url');
2 const Variants
= require("./variants");
4 module
.exports = function(wss
) {
6 let clients
= { "index": {} };
7 let games
= {}; //pending games (player sid)
8 for (const v
of Variants
)
11 wss
.on("connection", (socket
, req
) => {
12 const params
= new URL("http://localhost" + req
.url
).searchParams
;
13 const sid
= params
.get("sid");
14 const page
= params
.get("page");
15 clients
[page
][sid
] = socket
;
20 for (const v
of Variants
)
21 countings
[v
.name
] = Object
.keys(clients
[v
.name
]).length
;
22 socket
.send(JSON
.stringify({code:"counts",counts:countings
}));
26 // Send to every client connected on index an update message for counts
27 Object
.keys(clients
["index"]).forEach( k
=> {
28 clients
["index"][k
].send(JSON
.stringify({code:"increase",vname:page
}));
30 // Also notify potential opponents: hit all clients which check if sid corresponds
31 Object
.keys(clients
[page
]).forEach( k
=> {
32 clients
[page
][k
].send(JSON
.stringify({code:"connect",id:sid
}));
34 socket
.on("message", objtxt
=> {
35 let obj
= JSON
.parse(objtxt
);
39 if (!!clients
[page
][obj
.oppid
])
40 clients
[page
][obj
.oppid
].send(JSON
.stringify({code:"newmove",move:obj
.move}));
43 if (!!clients
[page
][obj
.oppid
])
44 socket
.send(JSON
.stringify({code:"pong"}));
47 if (!!clients
[page
][obj
.oppid
])
49 const oppId
= obj
.oppid
;
50 obj
.oppid
= sid
; //I'm oppid for my opponent
51 clients
[page
][oppId
].send(JSON
.stringify(obj
));
58 const oppId
= games
[page
]["id"];
59 const fen
= games
[page
]["fen"];
61 const mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
62 socket
.send(JSON
.stringify({code:"newgame",fen:fen
,oppid:oppId
,color:mycolor
}));
63 if (!!clients
[page
][oppId
])
64 clients
[page
][oppId
].send(JSON
.stringify({code:"newgame",fen:fen
,oppid:sid
,color:mycolor
=="w"?"b":"w"}));
67 games
[page
] = {id:sid
, fen:obj
.fen
}; //wait for opponent
70 if (!!clients
[page
][obj
.oppid
])
71 clients
[page
][obj
.oppid
].send(JSON
.stringify({code:"resign"}));
76 socket
.on("close", () => {
77 delete clients
[page
][sid
];
78 // Remove potential pending game
79 if (!!games
[page
] && games
[page
]["id"] == sid
)
83 // Send to every client connected on index an update message for counts
84 Object
.keys(clients
["index"]).forEach( k
=> {
85 clients
["index"][k
].send(JSON
.stringify({code:"decrease",vname:page
}));
88 // Also notify potential opponents: hit all clients which check if sid corresponds
89 Object
.keys(clients
[page
]).forEach( k
=> {
90 clients
[page
][k
].send(JSON
.stringify({code:"disconnect",id:sid
}));