我正在使用 socket.io 将数据消息从 RabbitMQ 流式传输到浏览器,但到目前为止,我只知道如何对服务器进行硬编码以订阅单个(预先指定的)路由键(在下面的代码中)是message.1
)。我想做的是创建一个 api,以便每个客户端(浏览器会话)可以订阅他们想要的任何路由键,并让 socket.io 仅将订阅的消息流式传输到这些客户端。这是我已经拥有的代码:
//app.js
var express = require('express'),
routes = require('./routes'),
api = require('./routes/api'),
http = require('http'),
path = require('path');
var amqp = require('amqp'),
rabbitMq = amqp.createConnection({ url: "amqp://guest:guest@localhost" },
{defaultExchangeName: "amq.topic"});
var app = module.exports = express(),
server = http.createServer(app),
io = require('socket.io').listen(server);
/**
* Configuration
*/
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
// development only
if (app.get('env') === 'development') {
app.use(express.errorHandler());
}
// production only
if (app.get('env') === 'production') {
// TODO
};
/**
* Routes
*/
// serve index and view partials
app.get('/', routes.index);
app.get('/partials/:name', routes.partials);
// JSON API
app.get('/api/name', api.name);
// redirect all others to the index (HTML5 history)
app.get('*', routes.index);
rabbitMq.on('ready', function () {
io.sockets.on('connection', function (socket) {
var exchange = rabbitMq.exchange('my-exchange',{durable:true});
var queue = rabbitMq.queue('my-queue',{durable: true});
queue.bind(exchange,'message.1'); // all messages
queue.subscribe(function (message) {
socket.broadcast.emit('message', {
msg: decodeURIComponent(message.data),
ts: Date()
});
console.log(message);
});
});
});
/**
* Start Server
*/
server.listen(app.get('port'),function() {
console.log("Express server listening on port " + app.get('port'));
});
我尝试从 app.js 中取出 rabbitMQ 代码并将其放入 api.js,但这似乎不起作用。任何关于此处下一步的建议或指导将不胜感激。我一直在网上搜索相关示例/教程,但似乎找不到任何合适的。