如何在 Ruby 中实现 Pubnub Presence 功能 [英] How to Implement Pubnub Presence feature in Ruby

查看:54
本文介绍了如何在 Ruby 中实现 Pubnub Presence 功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在 Rails 应用程序中使用 PubNub 实现用户呈现,但我没有找到有关如何在服务器端和客户端实现此功能的完整指南.

解决方案

PubNub Presence with Ruby and JavaScript

按照连接两个 PubNub SDK 之间的状态的简短指南,轻松开始使用 Ruby 和 JavaScript 中的 PubNub Presence.首先,您需要确保在您的服务器上安装了最新的 PubNub Ruby GEM 客户端 SDK.但在我们进入编码方面之前,我们可以先谈谈 PubNub Presence 实际上是什么.

PubNub 介绍

PubNub Presence 允许您提出问题谁在那里?",并以用户 ID 列表和谁的占用计数的形式收到回复目前在线.

通常您会在 PubNub 频道的上下文中问这个问题.用户连接到 PubNub 频道,以便从 PubNub 网络接收数据流.您可以通过任何有效的 UTF-8 字符串发布和订阅频道,从而通过频道控制流.有时您想通过请求频道上的当前活动和已连接用户列表来了解 PubNub 频道的当前状态.您可以使用 PubNub Presence 功能来完成此操作,该功能可提供您所寻求的答案.

PubNub Presence SDK

让我们首先列出为目标平台包含/加载 GEM 和 JavaScript SDK 的两个开始步骤(这次是 Ruby+JavaScript 组合).

安装 PubNub Ruby GEM

sudo gem install pubnub

接下来,您将确保在您的 JavaScript 客户端应用(通常是手机应用或网站应用)上运行最新的 JavaScript SDK 之一.

包含 PubNub JavaScript 客户端 SDK

<script src=http://cdn.pubnub.com/pubnub-3.4.2.min.js ></script>

既然您已经访问了 Ruby 和 JavaScript 的两个必要的基础 SDK 库,您就可以通过 PubNub 网络自由地接收/传输信息.接下来,我们将讨论如何轻松接收 PubNub 频道上发生的在线状态事件,以及如何使用 here_now() API 直接查询当前频道状态.

PubNub 开发控制台 - 状态

<块引用>

使用

  • PubNub 网络 JavaScript SDK - https://github.com/pubnub/javascript#simple-例子
  • I was wondering how to implement user presence with PubNub in Rails apps, but I didn't find a complete guide to how to implement this feature in both server and client side.

    解决方案

    PubNub Presence with Ruby and JavaScript

    Get started easily with PubNub Presence in Ruby and JavaScript by following this short guide which connects the state between the two PubNub SDKs. First you'll want to make sure you have the latest PubNub Ruby GEM client SDK install on your server. But before we get into the coding aspect we can talk about what PubNub Presence actually is.

    PubNub Presence Introduction

    PubNub Presence allows you to ask the question "Who is there?" and receive back an answer in the form of a List of UserIDs and an occupancy count of who is currently online right now.

    Usually you ask this question in the context of a PubNub Channel. User's connect to a PubNub Channel in order to receive a stream of data from the PubNub Network. You control the stream by way of Channels by publishing and subscribing to channels by any valid UTF-8 string. Sometimes you want to know the current state of the PubNub Channel by requesting the current activity and list of connected users on the channel. You can do this by using PubNub Presence feature which provides the answer you seek.

    PubNub Presence SDKs

    Let's get starte by listing the two starting steps of including/loading the GEM ans JavaScript SDKs for your target platforms (This time it's Ruby+JavaScript Combo).

    Install PubNub Ruby GEM

    sudo gem install pubnub
    

    Next you will ensure that you are running one of the latest JavaScript SDKs on your JavaScript Client App (usually a mobile phone app or website app).

    Include PubNub JavaScript Client SDK

    <script src=http://cdn.pubnub.com/pubnub-3.4.2.min.js ></script>
    

    Now that you have accessed the two necessary base SDK libs for Ruby and JavaScript, you are able to receive/transmit information freely over the PubNub Network. Next we'll talk about how you can easily receive presence events as they occur on your PubNub Channel and also how you can query directly for the current channel state with here_now() API.

    PubNub Dev Console - Presence

    Use the PubNub Developer's Console to Monitor Presence Events.

    You can use the PubNub Developer's Console to watch Presence Events as they occur. You will be able to see the event payload in JSON form in the presence section which is shown in the following image:

    There are three events "action"s you can receive including:

    • "join" - A new user joined the channel.
    • "leave" - A user left the channel.
    • "timeout" - A user dropped connection and timed out.

    PubNub Presence with REST

    PubNub Here Now

    With PubNub Presence you have access to TWO REST routes. The easiest route is the here_now() route.

    PubNub Presence with SDKs

    Example Source Code in JavaScript

    The following is an example of method in JavaScript to receive data on a Channel and also receive Presence Events for that channel as they occur in real-time. Also you will notice the paramaters that are passed to you in your Function Callback. This method allows you to receive a stream of data into your JavaScript Application. Note there is a second method to receive presence data (called here_now()) which we will cover a bit further down.

    <script>(function(){
        var pubnub = PUBNUB.init({
            subscribe_key : 'demo'
        });
    
        pubnub.subscribe({
            channel    : "hello_world",                        // YOUR CHANNEL.
            message    : function( message, env, channel ) {}, // RECEIVE MESSAGE.
            presence   : function( message, env, channel ) {   // PRESENCE EVENTS.
                console.log( "Channel: ",            channel           );
                console.log( "Join/Leave/Timeout: ", message.action    );
                console.log( "Occupancy: ",          message.occupancy );
                console.log( "User ID: ",            message.uuid      );
            }
    
        })
    })();</script>
    

    Example Source Code in Ruby

    Here is Ruby Code which is the ruby method to receive Presence Events in real-time as they occur. You can process the stream or (Firehose) of events as they come in. Note there is a second method to receive presence data (called here_now()) which we will cover a bit further down.

    require 'pubnub'
    
    pubnub = Pubnub.new(
        :publish_key   => 'demo', # publish_key only required if publishing.
        :subscribe_key => 'demo', # required
        :secret_key    => nil,    # optional, if used, message signing is enabled
        :cipher_key    => nil,    # optional, if used, encryption is enabled
        :ssl           => nil     # true or default is false
    )
    
    ## Receive Presence Events on a Channel
    pubnub.presence(
        :channel  => :hello_world,
        :callback => lambda { |event_data| puts(event_data) }
    )
    

    When an event occurs (such as a user joining) the output data will look like:

    {"action":"join", "timestamp":1364261400, "uuid":"9d497a30-3af2-4b67-a6b3-82f254711c11", "occupancy":4}
    

    on a User Disconnect, the presence event is triggered as:

    {"action":"leave", "timestamp":1364251540, "uuid":"9d497a30-3af2-4b67-a6b3-82f254711c11", "occupancy":3}
    

    and potentially in the event of an error/timeout:

    {"action":"timeout", "timestamp":1364251540, "uuid":"9d497a30-3af2-4b67-a6b3-82f254711c11", "occupancy":3}
    

    Here_Now in JavaScript

    There is a here_now() function available to you that allows you to issue a single REST request to the PubNub Network that gets the Current state of a channel's connectivity. The request looks like:

    <script>(function(){
        var pubnub = PUBNUB.init({
            subscribe_key : 'demo'
        });
    
        pubnub.here_now({
            channel  : 'hello_world',
            callback : function (message) { console.log(message) }
        });
    })();</script>
    

    and the response object will look like:

    {"uuids":["754e58b3-a79b-4d91-8f6c-5d994e43a310","175c2c67-b2a9-470d-8f4b-1db94f90e39e","fafd273d-9be5-4049-a6ce-653c467f7c5d"],"occupancy":3}
    

    Here_Now in Ruby

    Just like in JavaScript the same function for here_now() is available in Ruby too. Here is the ruby syntax version:

    require 'pubnub'
    
    pubnub = Pubnub.new(
        :publish_key   => 'demo', # publish_key only required if publishing.
        :subscribe_key => 'demo', # required
        :secret_key    => nil,    # optional, if used, message signing is enabled
        :cipher_key    => nil,    # optional, if used, encryption is enabled
        :ssl           => nil     # true or default is false
    )
    
    pubnub.here_now(
        :channel  => :hello_world,
        :callback => lambda { |event_data| puts(event_data) }
    )
    

    And the response object data is identical to what is available to you in JavaScript.

    {"uuids":["754e58b3-a79b-4d91-8f6c-5d994e43a310","175c2c67-b2a9-470d-8f4b-1db94f90e39e","fafd273d-9be5-4049-a6ce-653c467f7c5d"],"occupancy":3}
    

    Finally if you want to use the simple JSON REST interface provided by the PubNub Network, you can issue the following requests easily:

    curl http://pubsub.pubnub.com/v2/presence/sub_key/demo/channel/hello_world
    

    and the response output is identical:

    {"uuids":["754e58b3-a79b-4d91-8f6c-5d994e43a310","175c2c67-b2a9-470d-8f4b-1db94f90e39e","fafd273d-9be5-4049-a6ce-653c467f7c5d"],"occupancy":3}
    

    That's it! Super simple and easy to use PubNub Network Presence with Ruby on Rails and JavaScript. If you have any questions please contact PubNub directly and also visit the following links for more details:

    这篇关于如何在 Ruby 中实现 Pubnub Presence 功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆