Socket.io – 将数据从推送stream发送到客户端

我正在努力通过pusher-client-node将使用Socket.IO的数据stream发送到客户端。

我正在接收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中使用我的pusherstream。 因此,我的问题:如何连接我的Socket.IO代码与我的Pusher代码?

你需要使用socket / io房间 …

服务器:

 var channel = pusher.subscribe("ticker.160"); //subscribe to pusher //pass messages from pusher to the matching room in socket.io channel.bind("message", function (data) { io.to('ticker.160').emit('room-message', {room:'ticker.160', data:data}); }); ... io.on("connection", function (socket) { ... socket.on('join', function(room){ socket.join(room); }); socket.on('leave', function(room){ socket.leave(room); }); }); 

客户:

 io.emit('join','ticker.160'); io.on('room-message', function(message){ switch(message.room) { case 'ticker.160': return doSomething(message.data); ... } });