gpt4 book ai didi

javascript - Socket.io - 将数据从推送流发送到客户端

转载 作者:行者123 更新时间:2023-11-30 00:34:43 25 4
gpt4 key购买 nike

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

我像这样在 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 代码连接起来?

最佳答案

您需要使用 socket/io rooms ...

服务器:

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

关于javascript - Socket.io - 将数据从推送流发送到客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27721660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com