如何解决PubNub-发送“欢迎”连接消息
在用户连接到套接字后直接处理向用户直接发送消息的最佳方法是什么?
基本上,“今天的话是:青蛙”,但只会发送给刚连接的用户。
我的假设是,他们将加入global
频道以及与他们的uuid beholden-trans-am
匹配的频道。用户都是匿名的(这是网站上的公开流)
感谢任何指针!
解决方法
连接状态事件中的硬代码
如果每次客户端连接到新频道时只想说“欢迎”,则可以将该消息硬编码到状态回调的PNConnectedCategory
事件中,如下所示:
status: function(event) {
if (event.category == 'PNConnectedCategory') {
displayMessage('Welcome to channel,: ' + event.affectedChannels);
}
}
- 如果您一次订阅多个频道,那么所有这些频道都将位于
affectedChannels
属性中。 -
displayMessage
是您实现的自定义函数,用于在UI中的某处显示消息。这段代码是从PubNub JavaScript Quickstart app提取的,因此您可以使用它来快速开始 :)
存在Webhooks服务器端处理
这基本上是相同的解决方案,但来自您的服务器。您可以利用Presence Webhooks,以便在订阅者加入任何频道上的频道(存在join
事件)时通知您的服务器。
您的服务器代码(此处为Node示例)如下所示:
app.post("/myapp/api/v1/wh/presence",(request,response) => {
var event = request.body;
console.info('entering presence webhook for uuid/user: ' + event.uuid);
if ((!event) || (!event.action) || (!event.uuid)) {
console.info("could not process event: " + JSON.stringify(event));
response.status(200).end();
return;
}
if (event.action === "join") {
console.info(event.uuid + " has join " + event.channel);
////////////////////////////////////////////////////////
// THIS IS WHERE YOU ADD YOUR WELCOME MESSAGE CODE
////////////////////////////////////////////////////////
pubnub.publish({
channel : event.channel,message : {'welcome' : "Welcome to channel," + event.channel}
},function(status,response) {
// success/error check code goes here
});
}
if (event.action === "state-change" && event.state) {
console.info("state changed for " + event.uuid
+ " new state " + event.state);
}
if ((event.action === "leave") || (event.action === "timeout")) {
console.info(event.uuid + " has left or isn't reachable");
// use pubnub.wherenow() if needed.
}
response.status(200).end();
});
发布警告
如果您发布到该用户刚刚加入的频道,并且有其他用户订阅了该频道,那么每个人都会收到该欢迎消息,因此您可能希望将该消息发布到仅订阅该加入用户的频道至。这应该是一些众所周知的“专用”通道(至少对于您的服务器是众所周知的)。也许此频道是用户的UUID,所以您可以像这样发布消息:
pubnub.publish({
channel : event.uuid,// use the UUID as the channel name
message : {'welcome' : "Welcome to channel," + event.channel}
},
进一步的帮助
我希望这会为您如何实现此方法提供一些见解。如果您还有其他疑问,请联系PubNub Support,并提供有关您要执行的操作的完整详细信息,并在适用的情况下引用此SO帖子。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。