提问者:小点点

Node. js应用发送广播消息socket.io


我是新手到node. js和socket.io但我想写一个小应用程序广播一些值连接的客户端.我不知道两件事第一我如何能火socket.广播.emit或其他广播功能在我的其他功能?在我的应用程序中,我有一个函数,每秒计算一个值,我想发送这个值给所有的客户端.我的第二个问题是我如何得到这个消息在客户端和使用它在我的其他javascript功能?我看到这之前node.jssocket.io广播从服务器,而不是从一个特定的客户端?但未能做我想提前感谢这里是我的代码:

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个答案

匿名用户

因为第一个问题很简单,

在你的模块中,用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_moduleJS

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' });