node.js app发送广播消息socket.io

时间:2013-01-28 07:28:58

标签: javascript node.js websocket socket.io

我是node.js和socket.io的新手,但我想编写一个小应用程序来向连接的客户端广播一些值。 我首先不知道两件事如何在我的其他函数中触发socket.broadcast.emit或其他广播函数?在我的应用程序中,我有一个每秒计算一个值的函数,我想将此值发送给所有客户端。 我的第二个问题是我如何在客户端获取此消息并在其他javascript函数中使用它? 我之前看过这个 node.js + socket.io broadcast from server, rather than from a specific client?但未能做我想做的事 提前致谢 这是我的代码:

var cronJob = require('cron').CronJob;
var snmp = require('snmp-native');
//var oid = [1, 3, 6, 1, 2, 1, 1, 1, 0];
//var oid1 = [1,3,6,1,2,1,11,1];
//var oid2 = [1,3,6,1,4,1,2636,3,9,1,53,0,18];
//var oid3 = [1,3,6,1,2,1,2,2,1,11,18];
var intraffic = [1,3,6,1,2,1,2,2,1,10,18]; //inbound traffic
var outtraffic = [1,3,6,1,2,1,2,2,1,16,18]; //outbound traffic
var inpps = [1,3,6,1,4,1,2636,3,3,1,1,3,518]; //interface inbound pps
var outpps = [1,3,6,1,4,1,2636,3,3,1,1,6,518]; //interface out pps

var session = new snmp.Session({ host: '10.0.0.73', port: 161, community: 'Pluto@com' });
new cronJob('* * * * * *', function(){
    session.get({ oid:intraffic }, function (error, varbind) {
        var vb;
        if (error) {
            console.log('Fail :(');
        } else {
            vb=varbind[0];
            console.log(vb.oid + ' = ' + vb.value + ' (' + vb.type + ')');
        }

    });
}, null, true, "America/Los_Angeles");

1 个答案:

答案 0 :(得分:1)

第一个问题很简单,

在您的模块中,使用socket.io服务器实例创建名为io的变量,并将其导出到最后。如果所有函数都在同一个模块上,那么您只需要一个全局变量(仅对该模块是全局变量)

- mymodule.js -

var io = require('socket.io').listen(80); // Create socket.io server as usual
...
module.exports.io = io; // Add this at the end of mymodule.js


// Broadcast in the same module where the server is defined
io.sockets.emit('this', { will: 'be received by everyone' });

- other_module.js -

var wsserver = require( 'mymodule.js' ); // Require your module as usual and assign it to a variable
...
// Usage of socket server to broadcast a message in another module
wsserver.io.sockets.emit('this', { will: 'be received by everyone' });