我正在为小型多人游戏设置排行榜的网络套接字。
我尝试过io.configure(),但是最新版本中已经没有了。
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(process.env.PORT || 4000);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data){
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
var resultsCache = {};
var clientCache = {};
io.on('connection', client => {
client.on('joinRoom', clientData => {
const roomKey = clientData["key"];
const name = clientData["name"];
if (roomKey in resultsCache) {
if ((name in resultsCache[roomKey])){
client.emit("nameError", "Username already exists");
}else {
resultsCache[roomKey][name] = {}
client.emit("done")
}
}else{
resultsCache[roomKey] = {};
resultsCache[roomKey][name] = {};
clientCache[roomKey] = {}
client.emit("done")
}
console.log(resultsCache);
})
// room - [{name:{game1:0, game2: 1}}, {name: {game2}}, {}]
client.on("score", scoreData => {
const roomKey = scoreData["key"];
const name = scoreData["name"];
const game = scoreData["game"]
console.log(roomKey, name, game)
console.log(resultsCache)
resultsCache[roomKey][name][game] = scoreData["score"];
console.log(resultsCache)
if (game in clientCache[roomKey]){
clientCache[roomKey][game].push(client)
} else {
clientCache[roomKey][game] = [client]
}
var results = {}
for (var i in resultsCache[roomKey]){
const scoreCard = resultsCache[roomKey][i]
if (game in scoreCard){
results[i] = scoreCard[game]
}
}
console.log(results)
var sortedArr = Object.keys(results).map(function(key) {
return [key, results[key]];
});
// Sort the array based on the second element
sortedArr.sort(function(first, second) {
return second[1] - first[1];
});
var sortedDicts = []
for (var i in sortedArr){
var l = {}
l['name'] = sortedArr[i][0]
l['score'] = sortedArr[i][1]
sortedDicts.push(l)
}
//Result
console.log(sortedDicts);
// client.emit("results", sortedDicts);
for (var i in clientCache[roomKey][game]){
var clientUpdate = clientCache[roomKey][game][i]
clientUpdate.emit("results", sortedDicts)
}
})
// deleting client data on exit
client.on("exit", data=>{
const roomKey = data["key"];
const name = data["name"];
console.log(resultsCache);
console.log(clientCache);
console.log(roomKey, name)
delete resultsCache[roomKey][name];
for (var i in clientCache[roomKey]){
if (client in clientCache[roomKey][i]){
var index = clientCache[roomKey][i].indexOf(client);
delete clientCache[roomKey][i][index];
}
}
console.log(resultsCache);
console.log(clientCache);
})
});
在safari上,它运行得很好,但在chrome和Firefox上却不能。 在chrome中,它只会崩溃,而在Firefox中,如果有多个用户,则只会处理一个用户。