2017-01-27 70 views
0

我無法讓節點js識別除「消息」之外的其他任何頻道。頻道名稱「消息」被識別,但是當我將頻道名稱更改爲任何其他名稱時,節點不會訂閱並響應頻道名稱。節點js不會訂閱具有其他名稱的redis頻道

實施例:

var sub = redis.createClient(); 

sub.subscribe('message'); 

sub.on('message', function (channel, data) { 

    data = JSON.parse(data); 
    console.log('chat', channel, data); 

}); 

/* 
* Server 
*/ 

// Start listening for incoming client connections 
io.sockets.on('connection', function (socket) { 

    console.log('NEW CLIENT CONNECTED'); 


    socket.on('disconnect', function() { 
     console.log('DISCONNECT'); 
    //I've tried using unsubscribe to message to fix problem 
    //sub.unsubscribe('message'); 
    }); 

}); 

上面的代碼作品,並輸出到控制檯:

chat message { room: 1 } 
DISCONNECT 
NEW CLIENT CONNECTED 

下面的代碼不記錄頻道訂閱日誌:

新的客戶端連 DISCONNECT

var sub = redis.createClient(); 

sub.subscribe('chat'); 

//Does not output anything to console 
sub.on('chat', function (channel, data) { 

    data = JSON.parse(data); 
    console.log('chat', channel, data); 

}); 

/* 
* Server 
*/ 

// Start listening for incoming client connections 
io.sockets.on('connection', function (socket) { 

    console.log('NEW CLIENT CONNECTED'); 


    socket.on('disconnect', function() { 
     console.log('DISCONNECT'); 
    //I've tried using unsubscribe to message to fix problem 
    //sub.unsubscribe('message'); 
    }); 

}); 

redis的-CLI MONITOR:

1485546938.714486 [0 127.0.0.1:49881] "info" 
1485546938.717446 [0 127.0.0.1:49881] "subscribe" "message" 
1485546945.902959 [0 127.0.0.1:49897] "SELECT" "0" 
1485546945.903406 [0 127.0.0.1:49897] "PUBLISH" "message" "{\"room\":1}" 

1485546868.850918 [0 127.0.0.1:49857] "info" 
1485546868.853824 [0 127.0.0.1:49857] "subscribe" "chat" 
1485546875.332391 [0 127.0.0.1:49873] "SELECT" "0" 
1485546875.332861 [0 127.0.0.1:49873] "PUBLISH" "chat" "{\"room\":1}" 

回答

2

的參數總是 '消息' 而不管信道名的。它是這樣的:

sub.on("message", function (channel, message) { 
    console.log("sub channel " + channel + ": " + message); 
}); 
+0

如果你能提供我關於方法'上'的文件,我會非常感謝。 – user3325126

+0

@ user3325126我會在EventEmitter上閱讀:https://nodejs.org/api/events.html#events_emitter_on_eventname_listener – Josh