我正在使用socket.IO在NodeJS和Android中构建测验应用程序,
我从服务器发出事件quizzoStatus
时遇到问题,该事件第一次触发一次,第二次触发两次,依此类推。
我在这里附上我的代码段
///server side: NodeJS
socket.on('sendQuizzoAnsPoints', async (data)=>{
try {
const obj = JSON.parse(data);
const game = await QuizzoPlayModel.findOne({_id:obj.gameId});
const player = await UserModel.findOne({_id: game.playerId});
const opponent = await UserModel.findOne({_id: game.opponentId});
if(obj.userId == game.opponentId){
let update = {
opponentPoints: game.opponentPoints + obj.points || 0,
opponentWA: game.opponentWA + obj.wrongAns || 0,
};
await QuizzoPlayModel.findByIdAndUpdate(obj.gameId, update).lean().exec();
userNamespace.to(player.socketId).emit('quizzoStatus', {
fullName: opponent.fullName,
points: game.playerPoints + obj.points,
wrongAns: obj.wrongAns,
gameId: obj.gameId
});
}
if(obj.userId == game.playerId) {
let update = {
playerPoints: game.playerPoints + obj.points || 0,
playerWA: game.playerWA + obj.wrongAns || 0,
};
await QuizzoPlayModel.findByIdAndUpdate(obj.gameId, update).lean().exec();
userNamespace.to(opponent.socketId).emit('quizzoStatus', {
fullName: player.fullName,
points: game.playerPoints+ obj.points,
wrongAns: obj.wrongAns,
gameId: obj.gameId
});
}
} catch (e) {
console.log(e);
}
});
在这里,我收听一个名为sendQuizzoAnsPoints
的事件,然后在另一个名为quizzoStatus
的事件中向玩家或对手发出一个事件。
quizzoStatus
事件从服务器到Android多次触发。 在这里我附上了android代码
/// Android code
socket.emit("sendQuizzoAnsPoints", new Gson().toJson(quizzoStatusRequestDto));
socket.on("quizzoStatus", new Emitter.Listener(){
@Override
public void call(Object... args){
runOnUiThread(new Runnable(){
@Override
public void run(){
Log.e("opponet point", opponentPoints + " " + quizzoStatusResponseDto.getPoints());
}
});
}
});
答案 0 :(得分:1)
问题出在$html = file_get_contents("log.html");
// Split up your html into header, data row, and the bottom
$html_pieces = explode("<!--==xxx==-->", $html, 3);
// Show the table header
echo $html_pieces[0];
$path = './visitors.txt';
$visitor_log = fopen($path, 'r');
while (($line = fgets($visitor_log)) !== false) {
$string_split = explode("--", $line, 3);
// Generate a new line of $output from the data row of your $html_pieces
$output = str_replace("---date---", $string_split[0], $html_pieces[1]);
$output = str_replace("---browser---", $string_split[1], $output);
$output = str_replace("---ip---", $string_split[2], $output);
// And display, line-by-line
echo $output;
}
// All done, finish off your table
echo $html_pieces[2];
中。您每次都在分配新的侦听器而不删除它。您需要为该Android
侦听器创建一个变量,并在完成工作后将其Emmiter
或其他地方删除:
onDestroy
希望这会起作用