简体   繁体   中英

node.js app send broadcast message socket.io

I'm newbie to both node.js and socket.io but i want to write a small application to broadcast some values to connected clients. I don't know two thing first how can i fire socket.broadcast.emit or other broadcast functions in my other functions? in my app i have a function that calculate a value every second,and i want to send this value to all clients. my second question is how i get this message in clients and use it in my other javascript functions? i saw this before node.js + socket.io broadcast from server, rather than from a specific client? but failed to do what i want thanks in advance here is my code:

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");

For the first question is easy,

In your module, create a variable named io with the socket.io server instance and export it at the end. If all the functions are on the same module, you only need a global variable (that will be global only for that module)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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