【问题标题】:How to run script and pass arguments if client is connected over socket?如果客户端通过套接字连接,如何运行脚本并传递参数?
【发布时间】:2012-12-01 22:05:15
【问题描述】:

是否可以运行一些脚本,如果客户端连接传递参数给它,像这样:

 var io = require('socket.io').listen(http);
 io.sockets.on('connection', function (client) {
     console.log('Client connected');
     var notifikacija = function (array) {
         client.emit('populate', array);
     }
 });

 ///////////////////////////////////////////////////////////////////////

 setInterval(function(){
     var array = newArray();
     array[0]='test';
     notifikacija(array);
 }, 2000);

现在它显示错误:notifikacija 未定义。真是一场斗争……

【问题讨论】:

    标签: javascript node.js sockets


    【解决方案1】:

    notifikacija 函数在 io.sockets.on 处理程序的范围内是本地的。您希望它是全局的,以便您可以在 setInterval 中访问它:

    var notifikacija = function(){}; // just an empty function, in case it gets called before it has something to do
    var io = require('socket.io').listen(http);
    io.sockets.on('connection', function(client) {
         console.log('Client connected');
         notifikacija = function(array){ // once the client is available assign the function
             client.emit('populate', array);
         }  
    });
    
    setInterval(function(){
        var array = newArray();
        array[0]='test';
        notifikacija(array);
    }, 2000);
    

    这里是a blog post with some more information on scope in Javascript

    【讨论】:

    • @sauletasmiestas 你是对的。它不再在 notif.. 函数的范围内。我会更新我的答案。
    • 感谢它完成了这项工作,我还添加了数组作为全局元素:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 2017-11-23
    • 2015-02-08
    • 2017-05-26
    • 1970-01-01
    • 2019-11-19
    相关资源
    最近更新 更多