【问题标题】:PubNub - send a "welcome" connection messagePubNub - 发送“欢迎”连接消息
【发布时间】:2020-11-10 05:21:43
【问题描述】:

在用户连接到套接字后直接向用户发送消息的最佳方式是什么?

基本上是“今日话题:Frog”,但只发送给刚刚连接的用户。

我的假设是他们将加入 global 频道以及与他们的 uuid beholden-trans-am 匹配的频道。用户都是匿名的(这是网站上的公共流)

感谢您的指点!

【问题讨论】:

  • 欢迎信息来自哪里?您可以将其硬编码到 addListener 的状态回调中。在已连接状态下,显示欢迎消息。您可以使用 Presence Webhooks,让您的服务器获取该加入事件,然后将欢迎消息发布到用户刚刚加入的频道或他们的个人频道,以便只有该用户才能获得它。所以有几种不同的方法,这取决于你的要求。你浏览过 JS Quickstart 应用程序吗? pubnub.com/docs/platform/quickstarts/javascript
  • 有关 Presence Webhook 的更多信息...pubnub.com/docs/platform/presence/presence-webhooks

标签: javascript pubnub


【解决方案1】:

连接状态事件中的硬代码

如果您只想在每次客户端连接到新频道时说“欢迎”,您可以将该消息硬编码到状态回调的 PNConnectedCategory 事件中,如下所示:

status: function(event) {
  if (event.category == 'PNConnectedCategory') {
    displayMessage('Welcome to channel, : ' + event.affectedChannels);
  }
}
  • 如果您一次订阅多个频道,那么所有这些频道都将位于 affectedChannels 属性中。
  • displayMessage 是您实现的自定义函数,可在 UI 中的某处显示消息。此代码是从PubNub JavaScript Quickstart app 中提取的,因此您可以使用它来快速入门 :)

Presence Webhooks 服务器端处理

这本质上是相同的解决方案,但来自您的服务器。您可以利用Presence Webhooks,以便在订阅者在任何频道上加入频道(出席join 事件)时通知您的服务器。

您的服务器代码(此处为节点示例)如下所示:

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 帖子。

【讨论】:

    猜你喜欢
    • 2021-10-07
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 2021-06-10
    • 2021-02-22
    • 2021-10-05
    • 1970-01-01
    相关资源
    最近更新 更多