简体   繁体   English

socket.io发射三遍

[英]socket.io emit firing three times

I'll start by saying I've found several similar issues posted on this site. 首先,我发现在此站点上发布了一些类似的问题。 None of them apply to my situation though. 他们都不适合我的情况。

I have a server and client (as is the norm with node.js/socket.io) and call emit a socket event when a button is pressed. 我有一个服务器和一个客户端(node.js / socket.io的规范也是如此),并在按下按钮时调用发出套接字事件。 This works fine... Except it seems to emit three times (at least the server runs the function three times). 正常工作...除了似乎发出三遍(至少服务器运行该函数三遍)。 I've been staring at the code for way too long at this point and need another set of eyes. 在这一点上,我一直在盯着代码太久了,需要另一双眼睛。

Hopefully someone has an idea. 希望有人有一个主意。

client code: 客户代码:

importJS('/js/pages/admin_base.js',function(){
    var restartLMC = function(io){
        toggleLoad();
        var user = localStorage.getItem('User');
        io.emit('restart_request',{session: user});
    };
    AdminIO = new io('http://localhost:26266');
    AdminIO.on('restart_success',function(dat){
        toggleLoad();
        dropInfo(dat);
    });
    AdminIO.on('sendError',function(dat){
        dropInfo(dat,{level: 'error'});
    });
    AdminIO.on('restart_fail',function(dat){
        toggleLoad();
        dropInfo(dat,{level: 'error'});
    });
    $('#restart').on('click',function(){
        restartLMC(AdminIO);
    });
});

Admin code: 管理员代码:

process.stdout.write('\033c');
console.log('\x1b[36m', "Admin server starting...", '\x1b[0m');
var 
    ini = require('node-ini')
    , conf = ini.parseSync('../config.ini')
    , CS = require('../lm_modules/CoreSync.js')
    , CoreSync = new CS()
    , checkSession = function (session, callback) {
            var res;
            if (!CoreSync) { throw "Fatal error, there is no connection to the Core service!"; }
            if (CoreSync.sessions) {
                if (CoreSync.sessions[session]) {
                    res = CoreSync.sessions[session];
                    callback(res);
                }
                else {
                    CoreSync.sync('session', function (err, dat) {
                        if (CoreSync.sessions[session]) {
                            res = CoreSync.sessions[session];
                            callback(res);
                        } else { res = false; callback(res); }
                    });
                }
            } else {
                res = false; callback(res);
            }
            if (res === "undefined") { callback(false); }
        }
    , runCMD = function(cmd,errCB,callback){
        var
            command
            , args;
        if(cmd.cmd){ command = cmd.cmd; } else { command = cmd; }
        if(cmd.args){ args = cmd.args; }
        const spawn = require('child_process').spawn;        
        const ex = spawn(command, args);
        ex.stdout.on('data', (data) => {
            callback(data);
        });
        ex.stderr.on('data', (data) => {
            errCB(data);
        });
        ex.on('close', (code) => {

        });
    }    
    , executeCMD = function(cmd,callback){
        const exec = require('child_process').exec
              , cdw = (__dirname + '/../');
        exec(cmd, {cwd: cdw}, (err, stdout, stderr) => {
            if (err) {
                callback(err,null);
                return;
            }
            callback(stderr,stdout);
        });
    }    
    , io = require('socket.io').listen(26266) // can use up to 26485

console.log('\x1b[32m', "Admin server started.", '\x1b[0m');
console.log("Admin server listening at " + "http://" + conf["Server"]["binding"] + ":26266");
io.on('connection', function (socket) {   
    socket.on('restart_request', function(req){
        console.log('Recieved restart request');       
        var success = false
            , session = JSON.parse(req.session)
            , sessionID = session.sessionID;
        checkSession(sessionID, function (ses) {
            if (ses === false) { console.error('CheckSession failed: No session exists'); return; }
            if (ses.user.uuid !== session.uuid) { console.error('CheckSession failed: UUID mismatched'); return; }
            if (ses.user.role < conf['Permissions']['lm_restart']){ socket.emit('restart_fail','Insufficient permissions.'); return; }
            if(process.platform === 'win32'){            
                executeCMD('cd',function(err,res){
                    var errSent = false;
                    if(err){                        
                        console.error(err);
                        if(!errSent){ socket.emit('sendError','Restart failed'); }
                        errSent = true;
                        if(res === null){return;}
                    }
                    console.log(res);
                    socket.emit('restart_success','LM successfully restarted.');
                });                
            }
            else if(process.platform === 'linux'){

            }
        });
    });
});

For those of you who may have seen this and found it a curious question/situation... I found two parts to this. 对于那些可能已经看到这一问题并发现它是一个好奇的问题/情况的人……我发现了这两个部分。

The first part is the $().on binding. 第一部分是$()。on绑定。 For some reason (even though it's by no means called multiple times in the js code) adding unbind() in front of the binding resolved the issue in part... it cut the extra emits down from 3 to two (until I started another server app, then it went back up to three...) 出于某种原因(即使在js代码中没有多次调用),在绑定之前添加unbind()可以部分解决此问题...它将多余的发射从3减少到2(直到我开始另一个服务器应用,那么它又回升到三个...)

The other part I found was that (for some reason) the socket.io connection is being duplicated as many times as there are socket servers running. 我发现的另一部分是(由于某种原因)socket.io连接被复制的次数与正在运行的套接字服务器的次数相同。 More details on this issue here ... I believe that once the cause for this is found, my issue will be resolved. 对这个问题的更多细节在这里 ......我相信,一旦这种情况的原因是发现,我的问题将得到解决。

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

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