我正在使用 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);
});
==================================================== ===============所以,任何人都可以指导我!非常感谢您。