0

我正在使用 express 3x、node.js 和 redis。当我作为发布消息时,1 在订阅中收到此消息 2-3 次。(例如,当我刷新浏览器时,收到的消息每次增加 1)。下面是我的代码。


服务器端:~~~~~~~~~~

var express = require('express'),
    http = require('http')

var redis = require('redis');
var redisCli = redis.createClient();
var redisPub = redis.createClient();
var redisSub = redis.createClient();

redisCli.on("error", function (err) {
    console.error("\r\n Error generated from redis client ", err);
});
redisPub.on("error", function (err) {
    console.error("\r\n Error generated from redisPub ", err);
});
redisSub.on("error", function (err) {
    console.error("\r\n Error generated from redisSub ", err);
});

var server = http.createServer(app)
  , io = require('socket.io').listen(server);

server.listen(process.env.PORT);

app.configure(function () {
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.set('view options', { layout: false });

    app.use(express.favicon(__dirname + '/favicon.ico', { maxAge: 2592000000 }));
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    app.use(express.session({ secret: "myKey", store: new RedisStore({ maxAge: 86400000, client: redisCli }), cookie: { maxAge: 86400000} }));
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express.static(__dirname + '/static'));
});

io.configure(function () {
    io.enable('browser client minification');  // send minified client
    io.enable('browser client etag');          // apply etag caching logic based on version number
    io.enable('browser client gzip');          // gzip the file

    io.set('log level', 1);
    io.set("flash policy server", false);
    io.set("transports", ["jsonp-polling", "xhr-polling"]);
});

io.sockets.on('connection', function (client) {
    console.log("server - redisSub.subscribe from io.on.connection");
    redisSub.unsubscribe();
    redisSub.subscribe("announcement");

    redisSub.on("message", function (channel, message) {
        io.sockets.emit('announcement', message);
    });

    client.on('disconnect', function () {
        redisSub.unsubscribe("announcement");
        redisSub.quit();
    });

});

app.post('/PublishMessage', function (req, res) {
    redisPub.publish("announcement", req.body.users);

    res.setHeader('Cache-Control', 'max-age=0, must-revalidate, no-cache, no-store');
    res.setHeader('Connection', 'keep-alive');
    res.contentType('application/json');
    res.setHeader('Expires', new Date().addYears(-10));
    res.json({ result: 'ok' });
});

客户端~~~~~~~~~

    this.socket = io.connect('http://XXX.XXX.X.XXX/', { transports: ['jsonp-polling', 'xhr-polling'] });
    this.socket.on('connect', function () {
        alert("client - Socket client connect");
    });
    this.socket.on('announcement', function (msg) {
        alert("clientside - announcement ");
        var nUsers = parseInt($('#Summary>article>p:last').text(), 10) + parseInt(msg, 10);
        $('#Summary>article>p:last').text(nUsers);
    });

==================================================== ===============所以,任何人都可以指导我!非常感谢您。

4

1 回答 1

6

我从未使用过 socket.io,但在我看来,您的连接处理程序过于复杂。

在处理程序内部,您似乎没有对连接做出反应(例如发出“用户连接”事件)或以任何方式修改单个套接字连接的行为。

正在做的是反复订阅和取消订阅一个redisSub客户。我在这里可能是错的,但我认为您不需要或不应该这样做。

相反,您应该在连接处理程序之外子“通知”一次,因为您不需要在每个连接上子/取消子这个全局客户端。喜欢:

// Move this subscription outside of the connection handler, and you shouldn't
// have to continue to sub/unsub or otherwise manage it.
redisSub.on("message", function (channel, message) {
    io.sockets.emit('announcement', message);
});

// Since you're not reacting to connections or doing anything with individual
// connection sockets, you don't really have anything to do in this handler.
io.sockets.on('connection', function (socket) {
  // if you ONLY wanted to emit to this socket, you'd do it here
  //socket.emit("announcement", "just for this connection")
});
于 2012-11-24T16:06:44.003 回答