我基本上想要一个70秒的倒数计时器,重置为70,这是一个infinte倒数计时器。计时器重新启动时,新游戏开始。 唯一的问题是,如果我把计数器放在IO.on(连接)中,新的计时器启动时,新的计时器启动,然后计时器混乱,因为它需要在所有客户端(Android应用程序)上显示完全相同的计时器。我尝试将设置间隔设置在io.on之上,但它不会每秒更新只给出一个单值
下面是我的服务器代码
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var mysql = require('mysql');
var players = [];
var wingames ;
var db = mysql.createConnection({
host: 'localhost',
user: 'vaibhav_spinner',
database: 'spinapi',
})
var newGameid = 1;
db.connect(function(err){
if (err) console.log(err)
})
server.listen(11694, function(){
console.log("Server is now running...");
});
var countdown = 70;
///
io.on('connection', function(socket){
console.log("Player Connected!");
if(players.length==1){
var countdown = 70;
var countdowner = setInterval(function() {
countdown--;
io.sockets.emit('timer', { countdown: countdown });
socket.emit('lastwins',wingames);
console.log(countdown);
if (countdown==0) {
console.log("starting game");
countdown = 70;
newGameid ++;
console.log(newGameid);
}
}, 1000);
}
socket.emit('getPlayers', players);
socket.emit('newgameid',{newgame: newGameid});
socket.broadcast.emit('newPlayer', { id: socket.id });
socket.on('disconnect', function(){
console.log("Player Disconnected");
socket.broadcast.emit('playerDisconnected', { id: socket.id });
for(var i = 0; i < players.length; i++){
if(players[i].id == socket.id){
players.splice(i, 1);
}
}
});
socket.on('getcoins',function(data){
var email = data.uname;
console.log(" userEamil "+email);
db.query("SELECT * FROM userinfo WHERE uemail = ?",[email] ,function (err, result, fields) {
if(err) throw err;
console.log(result);
var ecoin = result[0].uCoins;
console.log(" userCoins "+ecoin)
io.emit('ucoins', ecoin);
}); });
socket.on('updatecoins',function(data){
console.log("data= "+data.toString());
var email = data.uname;
var ucoins = data.ucoins;
console.log(" userEmail "+email,"ucoins"+ucoins);
db.query("UPDATE userinfo set uCoins = ? WHERE uemail = ?",[ucoins,email],function (err, result, fields) {
if(err) throw err;
console.log(result.affectedRows + " record(s) updated");
});
});
// socket.on('getwinner',winnerbet(){
//
// });
players.push(new player(socket.id, 0, 0));
});
function player(id, x, y){
this.id = id;
this.x = x;
this.y = y;
}
我尝试了这样的方法:如果players.length == 1那么计时器应该启动而不是所有连接。但仍然无法使其正确。我的android端代码正确获取所以我没有问题wi 那个