简体   繁体   English

Node.js-Socket.IO发出多个回调

[英]Node.js - Multiple Callbacks on Socket.IO Emit

I have some issues with my node.js application. 我的node.js应用程序存在一些问题。 Ill send a basic request with the socket.io-client to a masterserver. 它将带有socket.io-client的基本请求发送到主服务器 The masterserver checks the ID and if it's valid he outputs valid token. 主服务器检查ID,如果有效,则输出有效令牌。 The problem is when I click on the client the second time the button it will stack the request on the masterserver and outputs the console.log x2. 问题是,当我第二次单击客户端上的按钮时,它将把请求堆叠在主服务器上并输出console.log x2。

Client: 客户:

function CheckAuthToken(authtoken, clid, callback){
   var token_state;
   console.log("Checking authtoken: " +authtoken);
   authsocket.emit('auth-token-check', {token: authtoken, clid: clid});
   authsocket.on('auth-token-check-callback', function(authresult){
      if(authresult.clid == clid){
        if(authresult.state ==  "token-valid"){
         token_state = "valid";
            callback(token_state);
      }else{
         token_state = "invalid";
            callback(token_state);
      }
    }
  });
}

AuthServer: 验证服务器:

socket.on('auth-token-check', function(data){
    mysqlconnection.query('SELECT * FROM `player_token` WHERE `token` = ?', [data.token], function (error, results, fields) {
      if(results.length > 0){
        socket.emit('auth-token-check-callback', {state: 'token-valid',clid: data.clid});
      }else{
        socket.emit('auth-token-check-callback', {state: 'token-invalid',clid: data.clid});
      }
    });
});

What am I doing wrong? 我究竟做错了什么?

Solution

Instead of adding all the time persistent Event Listener ( authsocket.on() ) use authsocket.once. 与其添加所有持久性事件监听器(authsocket.on()),不如使用authsocket.once。

That fixes my problem. 那解决了我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM