所以...我出于某种原因决定完全去socket.io服务器端处理,而不是路由帖。但是我遇到了一个函数只能工作一次的问题。第二次,一切都很好,除了数据库没有更新。 (背景中可能还有其他问题,但我似乎无法找到它)......哦!并且客户端值仅发出总是发出1,并且不会得到2,3,4等等。
客户端发出:
$('#battle-wrapper').on('click', 'button#battlebutton', function (event) {
event.preventDefault();
socket.emit('fight mob', $('#mobs').val());
console.log($('#mobs').val());
});
Socket.io代码:
socket.on('fight mob', function () {
var session = socket.handshake.session;
// Player Variables
var userMhp = session.userdata.tough;
var userHp = 10;
var userDmg = session.userdata.str;
var userDef = session.userdata.tough;
// Mob Variables
var mobid = 1;
var mobMhp = Math.floor(mobid * 50);
var mobHp = 100;
var mobDmg = 5;
var mobDef = 5;
// Statistic variables
var dmgdeltmob = 0;
var dmgdeltuser = 0;
var rounds = 0;
// Strings
// var userVictory = '';
// var mobVictory = '';
// var userDefeat = '';
// var mobDefeat = '';
// Turn Variables
var userTurn = true;
//start battle loop
while (userHp > 0 && mobHp > 0) {
// Start BATTLE
if (userTurn === true) {
dmgdeltmob = userDmg;
// mobHp = mobHp - dmgdeltmob;
rounds += 1;
userTurn = false;
} else if (userTurn === false) {
dmgdeltuser = mobDmg;
userHp = userHp - 10;
rounds += 1;
userTurn = true;
}
}
// Start end of battle Calculations
if (userHp <= 0) { // Defeat
console.log('Lost');
let sql = 'UPDATE users SET ? WHERE id = ?';
let post = {
silver: session.userdata.silver + 1,
};
db.query(sql, [post, session.userdata.id], function (err) {
console.log('1 Silver Success');
var data = post.silver;
socket.emit('mob test', data);
return;
});
} else {
console.log('Won');
}
});
答案 0 :(得分:1)
我找到了答案,也许不是最好的解决方案,实际上它可能不是。但这就是我所做的,我创建了一个调用登录的会话处理函数,并在刷新时:
function sessionHandler() {
// Adding the logged in user to session
var userId = session.passport.user;
var sql = 'SELECT * FROM users WHERE id = ?';
var query = db.query(sql, userId, function (err, rows) {
session.userdata = rows[0];
session.save();
var dataObj = session.userdata;
socket.emit('start up', dataObj);
usersConnected++;
io.emit('users online', usersConnected);
console.log(usersConnected);
});
}
这是处理登录/刷新的基本逻辑。遗憾的是,我似乎需要将所有逻辑添加到函数本身中。因为一切都在函数外部返回undefined,但在同一个块内。
// User logs in
if (session.passport === undefined) {
socket.emit('not logged', destination);
} else {
if (session.userdata === undefined) {
sessionHandler();
// console.log(session.userdata.username + ' logged in');
} else {
if (session.userdata) {
delete session.userdata;
session.save();
sessionHandler();
}
// console.log(session.userdata.username + ' refreshed their session');
}
}