我有一个应用程序,我使用Node js,socket io和redis实现了通知。
我在节点js中成功配置了发布者和订阅者。使用socket io我可以在客户端显示消息,就像实时一样。
我的设计是1个发布者发布到许多频道,每个用户只听他自己的频道。
我发布到channel1和channel2,并且由于用户只收听他们的频道,他们只收到他们各自的消息一次。
直到现在它运作良好,顺利。
但是我的问题开始了。当互联网脱机时,它会尝试重新连接,当它再次建立连接时,在每次发布时它都会开始订阅两次,因为这些信息显示两次。
我的代码在服务器用户端是这样的
io.sockets.on('connection', function (socket) {
var channelName = "channel"+socket.handshake.query.ch;
console.log("=======================================================================");
console.log("Connected to client - ["+socket.id+"] for ["+channelName+"]");
console.log("Transport Method - ["+io.transports[socket.id].name+"]");
console.log("=======================================================================");
try{
var client = redis.createClient();
client.on("connect",function(){
client.subscribe(channelName)?console.log("channel subscribed to {"+channelName+"}"):console.log("Not Subscribed to {"+channelName+"}");
client.on("message", function(channel,message){
console.log("=======================================================================");
console.log("Got message ["+message+"] in ["+channel+"]");
socket.emit("notification"+channel, { msg: message });
console.log("=======================================================================");
});
});
}catch(e){
console.log("Redis server is not running !!");
}
socket.on('disconnect', function(){
console.log("Disconnected From client !!");
});
});
在客户端,我的代码是这样的
<script src="localhost:3000/socket.io/socket.io.js"></script>
<script>
// For one client ch=1 and for another ch=2
var socket = io.connect("localhost:3000",{ query: "ch=1", "try multiple transports":false});
socket.on('connect', function(data){
$("div#status").html("<div class='connected'></div><span>connected</span>");
});
// For one client event is notificationchannel1 and for another client event is notificationchannel2
socket.on('notificationchannel1',function(data){
$("div#notification-div").append(data.msg);
});
socket.on('connecting', function(data){
$("div#status").html("<div class='connecting'></div><span>connecting</span>");
});
socket.on('disconnect', function(data){
$("div#status").html("<div class='disconnected'></div><span>disconnected</span>");
});
socket.on('reconnecting', function(data){
$("div#status").html("<div class='reconnecting'></div><span>reconnecting...</span>");
});
</script>
请告诉我我缺少的东西。