【发布时间】:2014-12-31 13:13:09
【问题描述】:
我正在努力使用 Socket.IO 将通过 pusher-client-node 使用的数据流发送到客户端。
我在 Node.JS 中像这样接收我的数据:
var API_KEY = 'cb65d0a7a72cd94adf1f';
var pusher = new Pusher(API_KEY, {
encrypted: true
});
var channel = pusher.subscribe("ticker.160");
channel.bind("message", function (data) {
//console.log(data);
});
我的数据,不断进来,看起来像这样:
{ channel: 'ticker.160',
trade:
{ timestamp: 1420031543,
datetime: '2014-12-31 08:12:23 EST',
marketid: '160',
topsell: { price: '0.00007650', quantity: '106.26697381' }}
我的 Socket.IO 代码如下所示:
/**
* Socket.io
*/
var io = require("socket.io").listen(server, {log: true});
var users = [];
var stream = channel.bind("message", function (data) {
console.log(data);
});
io.on("connection", function (socket) {
// The user it's added to the array if it doesn't exist
if(users.indexOf(socket.id) === -1) {
users.push(socket.id);
}
// Log
logConnectedUsers();
socket.emit('someevent', { attr: 'value' } )
stream.on("newdata", function(data) {
// only broadcast when users are online
if(users.length > 0) {
// This emits the signal to the user that started
// the stream
socket.emit('someevent', { attr: 'value' } )
}
else {
// If there are no users connected we destroy the stream.
// Why would we keep it running for nobody?
stream.destroy();
stream = null;
}
});
// This handles when a user is disconnected
socket.on("disconnect", function(o) {
// find the user in the array
var index = users.indexOf(socket.id);
if(index != -1) {
// Eliminates the user from the array
users.splice(index, 1);
}
logConnectedUsers();
});
});
// A log function for debugging purposes
function logConnectedUsers() {
console.log("============= CONNECTED USERS ==============");
console.log("== :: " + users.length);
console.log("============================================");
}
我对 Node.JS 和 Socket.IO 还很陌生,并且很难在 Node.JS 中使用我的推送流。因此我的问题是:如何将我的 Socket.IO 代码与我的 Pusher 代码连接起来?
【问题讨论】:
-
您引用的Pusher Node库(npmjs.com/package/pusher)是用于向Pusher发布信息,而不是用于消费数据。您在“我正在像这样在 nodejs 中接收我的数据:”之后提供的代码对您引用的库无效。该代码仅在使用 Pusher JS 库时在 Web 浏览器中有效:github.com/pusher/pusher-js
-
@leggetter 谢谢你的回答!但是,我在尝试 socket.io 连接时在同一个 nodeJS 实例中运行推送脚本,并且我不断收到数据...
-
您在问题 (npmjs.com/package/pusher) 中引用的 Node.js 库是否不正确?以下库确实提供了您在问题中显示的 API:github.com/dirkbonhomme/pusher-client-node
-
@leggetter 真的很抱歉,我以为这个库和我从github得到的一样。你完全正确!!!这个github.com/dirkbonhomme/pusher-client-node是我用来订阅推送服务的库。
标签: javascript node.js sockets socket.io pusher