0

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");
Community
  • 1
  • 1
user1229351
  • 1,985
  • 4
  • 20
  • 24

1 Answers1

2

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' });
JR.
  • 1,401
  • 1
  • 11
  • 9