只是想了解为什么我的 pubnub javascript 代码没有收到来自 channel 的消息。我可以订阅和发布,但是如果另一个浏览器发送新的发布消息,另一个浏览器将无法接收消息。这是我的代码:
$(document).ready(function () {
var pubnub = PUBNUB.init({
subscribe_key: 'subscribe-key-here',
publish_key: 'publish-key-here'
});
pubnub.subscribe({
channel : "my-channel",
message : function(m){ console.log(m) },
callback : function (message) { console.log("callback: ", message)},
connect : function() {
console.log("Connected")
pubnub.publish({
channel: 'my_channel',
message: { "color" : "blue" },
callback : function(details) {
console.log(details)
}
});
},
disconnect : function() { console.log("Disconnected") },
reconnect : function() { console.log("Reconnected") },
error : function() { console.log("Network Error") },
restore : true
})
});
顺便说一句,这段代码正在我的 nodejs 本地主机服务器以及 chrome 和 firefox 浏览器中运行/测试。
最佳答案
代码错误 - 您的 channel 名称有错别字:
subscribe
使用my_channel
publish
使用my-channel
此外,您在 subscribe 中使用了两个意义相同的参数: message
是 callback
还有你的publish , success
是 callback
的别名(在 JavaScript/Node v3.7.20+ 中),它被推荐(只是因为它更有意义)。
我已经从您的subscribe
中删除了callback
参数,并在下面的代码中将callback
替换为success
。
更正后的代码:
$(document).ready(function () {
var pubnub = PUBNUB.init({
subscribe_key: 'subscribe-key-here',
publish_key: 'publish-key-here'
});
pubnub.subscribe({
channel : "my_channel",
message : function (message) { console.log("callback: ", message)},
connect : function() {
console.log("Connected")
pubnub.publish({
channel: 'my_channel',
message: { "color" : "blue" },
success : function(details) {
console.log(details)
}
});
},
disconnect : function() { console.log("Disconnected") },
reconnect : function() { console.log("Reconnected") },
error : function() { console.log("Network Error") },
restore : true
})
});
关于javascript - 由于某种原因,Pubnub javascript 未收到回调或消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35076486/