【问题标题】:node.js app send broadcast message socket.ionode.js 应用程序发送广播消息 socket.io
【发布时间】:2013-01-11 12:24:26
【问题描述】:

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

【问题讨论】:

  • 似乎您给出的其他问题为您提供了解决方案。你有任何错误吗?到目前为止,您可以发布您的代码吗?
  • 到目前为止我没有更改代码,因为我不知道该怎么做。我不知道如何将我的值从其他函数发送到广播中
  • 你能发布你的Other函数吗?
  • Jayantha 我在我的问题帖子中发布了我的函数,它是 snmp 函数,每秒从设备获取一些值(使用 crone)我需要将此值(vb.value)广播到所有连接的客户端

标签: javascript node.js websocket socket.io


【解决方案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' });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    相关资源
    最近更新 更多