ios pusher使用
by Rahat Khanna
通过拉哈特·汉娜
如何使用JavaScript和Pusher实时更新用户状态 (How to update a User’s Status in realtime using JavaScript and Pusher)
“Hey, what’s up?” is not a phrase we need to ask someone these days. These days knowing what someone is up to has become so easy, because we keep seeing updated statuses for all our friends on WhatsApp, Snapchat, Facebook and so on.
“嘿,怎么了?” 这几天我们不是要问别人这个词。 如今,知道某人的举动变得如此容易,因为我们不断在WhatsApp,Snapchat,Facebook等上看到所有朋友的最新状态。
In this article, we will learn how we can update a user’s status in a realtime component along with a list of all members who are online.
在本文中,我们将学习如何在实时组件中更新用户状态以及所有在线成员的列表。
We will be using Node.js as the application server, Vanilla JavaScript in the front-end, and Pusher for realtime communication between our server and front-end.
我们将使用Node.js作为应用程序服务器,前端使用Vanilla JavaScript,并使用Pusher进行服务器与前端之间的实时通信。
We will build an app, which will be like your friends list or a common chat room, where you can see who’s online and what’s their latest status update in realtime. We will learn about Pusher’s presence channel and how to know about the online members on this channel.
我们将构建一个应用程序,就像您的朋友列表或公共聊天室一样,您可以在其中实时查看谁在线以及他们的最新状态。 我们将了解Pusher的状态频道以及如何了解该频道的在线成员。
We will be building the following components during this blog post:
在此博客文章中,我们将构建以下组件:
Node.js Server using Express.js Framework:
使用Express.js框架的Node.js服务器:
/register API — In order to register/login a new user to our channel and server by creating their session and saving their info
/ register API-为了通过创建他们的会话并保存他们的信息来将新用户注册/登录到我们的频道和服务器
/isLoggedIn API — To check if a user is already logged in or not in case of refreshing the browser
/ isLoggedIn API-在刷新浏览器的情况下检查用户是否已经登录
/usersystem/auth API — Auth validation done by Pusher after registering it with our app and on subscribing to a presence or private channel
/ usersystem / auth API-由Pusher在我们的应用程序中注册并订阅状态或私人频道后完成的身份验证
/logout API — To logout the user and remove the session
/ logout API-注销用户并删除会话
Front-End App using JavaScript:
使用JavaScript的前端应用程序:
- Register/Login Form — To register/login a new user by filling in their username and initial status 注册/登录表单—通过填写用户名和初始状态来注册/登录新用户
- Members List — To see everyone who is online and their updated statuses 成员列表—查看所有在线用户及其最新状态
- Update Status — To click on the existing status and update it on blur of the status text edit control 更新状态-单击现有状态并在状态文本编辑控件模糊时对其进行更新
Find here the link to the Github Repository for reference.
推杆简介 (Introduction to Pusher)
Pusher is a platform which abstracts the complexities of implementing a realtime system on our own using WebSockets or Long Polling. We can instantly add realtime features to our existing web applications using Pusher, as it supports a wide variety of software development kits (SDKs).
Pusher是一个平台,该平台抽象了使用WebSockets或Long Polling自己实现实时系统的复杂性。 我们可以使用Pusher立即将实时功能添加到我们现有的Web应用程序中,因为它支持各种软件开发工具包(SDK)。
Integration kits are available for a variety of front-end libraries like Backbone, React, Angular, and jQuery — and also back-end platforms/languages like .NET, Java, Python, Ruby, PHP, and GO.
集成工具包可用于各种前端库(例如Backbone,React,Angular和jQuery)以及后端平台/语言(如.NET,Java,Python,Ruby,PHP和GO)。
使用Pusher注册 (Signing up with Pusher)
You can create a free account in Pusher here. After you signup and login for the first time, you will be asked to create a new app as seen in the image below. You will have to fill in some information about your project, and also provide the front-end library or back-end language you will be building your app with.
您可以在推创建一个免费帐户这里 。 首次注册并登录后,将要求您创建一个新应用,如下图所示。 您将必须填写有关项目的一些信息,并提供用于构建应用程序的前端库或后端语言。
For this particular article, we will be selecting JavaScript for the front-end and Node.js for the back-end as seen in the image above.
对于这篇特定的文章,我们将为前端选择JavaScript,为后端选择Node.js,如上图所示。
This will just show you a set of starter sample codes for these selections, but you can use any integration kit later on with this app.
这只会为您显示这些选择的一组入门示例代码,但是您以后可以在此应用程序中使用任何集成套件。
Node.js服务器 (Node.js Server)
Node.js should be installed in the system as a prerequisite to this project. Now let’s begin building the Node.js server and all the required APIs using Express. Initialize a new node project by the following command:
应将Node.js作为此项目的前提条件安装在系统中。 现在,让我们开始使用Express构建Node.js服务器和所有必需的API。 通过以下命令初始化新的节点项目:
npm init
安装依赖项 (Installing Dependencies)
We will be installing the required dependencies like Express, express-session, Pusher, body-parser, cookie-parser by the following command:
我们将通过以下命令安装所需的依赖项,例如Express,express-session,Pusher,body-parser,cookie-parser:
基础服务器 (Foundation Server)
We will now create the basic foundation for the Node.js Server and also enable sessions in it using express-session
module.
现在,我们将为Node.js服务器创建基础,并使用express-session
模块在其中启用会话。
In the above code, we have created a basic Express server, and using the method .use
we have enabled cookie-parser, body-parser, and a static file serving from public
folder. We have also enabled sessions using express-session
module. This will enable us to save user information in the appropriate request session for the user.
在上面的代码中,我们已经创建了一个基本的Express服务器,以及使用该方法.use
我们支持cookie的解析器,身体分析器,并从服务于静态文件public
文件夹。 我们还使用express-session
模块启用了会话。 这将使我们能够在适当的用户请求会话中保存用户信息。
添加推送器 (Adding Pusher)
Pusher has an open source npm module for Node.js integrations, which we will be using. It provides a set of utility methods to integrate with Pusher APIs using a unique appId
, key
and a secret
. We will first install the Pusher npm
module using the following command:
Pusher有一个用于Node.js集成的开源npm模块,我们将使用它。 它提供了一套实用的方法采用了独特的带有推进器的API集成appId
, key
和一个secret
。 我们将首先使用以下命令安装Pusher npm
模块:
npm install pusher --save
Now, we can use require
to get the Pusher
module and to create a new instance passing an options object with important keys to initialize our integration. For this article, I have chosen random keys — you will have to obtain them for your app from the Pusher dashboard.
现在,我们可以使用require
获取Pusher
模块并创建一个新的实例,该实例通过带有重要键的options对象来初始化我们的集成。 在本文中,我选择了随机密钥-您必须从Pusher仪表板为您的应用程序获取它们。
You will have to replace the appId
, key
and a secret
with values specific to your own app. After this, we will write code for a new API which will be used to create a new comment.
您将必须替换appId
, key
key
以及包含特定于您自己的应用程序的值的secret
。 之后,我们将为新的API编写代码,这些代码将用于创建新的注释。
注册/登录API (Register/Login API)
Now, we will develop the first API route of our application through which a new user can register/login and make themselves available on our app.
现在,我们将开发应用程序的第一个API路线,新用户可以通过该路线注册/登录并使自己在我们的应用程序中可用。
In the above code, we have exposed a POST
API call on the route /register
which would expect username
and status
parameters to be passed in the request body. We will be saving this user info in the request session
.
在上面的代码中,我们公开了路由/register
上的POST
API调用,该调用期望username
和status
参数在请求正文中传递。 我们将在request session
保存此用户信息。
用户系统身份验证API (User System Auth API)
In order to enable any client subscribing to Pusher Private
and Presence
channels, we need to implement an auth
API which would authenticate the user request by calling Pusher.authenticate
method at the server side. Add the following code in the server in order to fulfill this condition:
为了启用任何订阅Pusher Private
和Presence
通道的客户端,我们需要实现一个auth
API,该API将通过在服务器端调用Pusher.authenticate
方法来认证用户请求。 为了满足此条件,请在服务器中添加以下代码:
We need to provide the specific route in the initialization of the Pusher client side library, which we will see later. The Pusher client library will automatically call this route and pass in the channel_name
and socket_id
properties. We will simultaneously get the user information from the user session object and pass it as presenceData
to the Pusher.authenticate
method call.
我们需要在Pusher客户端库的初始化中提供特定的路由,稍后我们将进行介绍。 Pusher客户端库将自动调用此路由,并传入channel_name
和socket_id
属性。 我们将同时从用户会话对象获取用户信息,并将其作为presenceData
传递给Pusher.authenticate
方法调用。
IsLoggedIn和注销API (IsLoggedIn and Logout API)
If the user refreshes the browser, the client side app should detect if the user is already registered or not. We will implement an isLoggedIn
API route for this. Also, we need a logout
route to enable any user to logout from the app.
如果用户刷新浏览器,则客户端应用程序应检测用户是否已注册。 我们将为此实现一个isLoggedIn
API路由。 另外,我们需要logout
路径,以使任何用户都可以从应用程序注销。
使用Vanilla JavaScript的前端应用 (Front-End App using Vanilla JavaScript)
We will now be developing the front-end app to register a new user with an initial status and see the members who are online and their statuses. We will also build the feature for the logged-in user to update their users and all other users will see the updated status in realtime.
现在,我们将开发前端应用程序,以注册具有初始状态的新用户,并查看在线成员及其状态。 我们还将为登录用户构建功能,以更新其用户,所有其他用户将实时看到更新状态。
步骤1:创建一个名为public的文件夹并创建一个index.html文件 (Step 1: Create a folder named public and create an index.html file)
We have already written code in our server.js
to serve static content from public
folder, so we will write all our front-end code in this folder.
我们已经在server.js
编写了用于从public
文件夹提供静态内容的代码,因此我们将在此文件夹中编写所有前端代码。
Please create a new folder public
and also create an empty index.html
file for now.
请创建新文件夹public
,也可以创建一个空index.html
现在文件。
第2步:将样板代码添加到我们的index.html (Step 2: Add Boilerplate Code to our index.html)
We will be adding some basic boilerplate code to set up the base structure for our web app like Header
, and Sections
where the registration form and the members list can be placed.
我们将添加一些基本的样板代码,以设置Web应用程序的基本结构,例如Header
和可放置注册表单和成员列表的Sections
。
In the above boilerplate code, we have referenced our main JavaScript file app.js
and the Pusher client side JavaScript library. We also have a script tag where we will place the template for a member row in the member list. Also, we have two empty div tags with ids me
and membersList
to contain the logged in member name and info, as well as the list of all other members with their status.
在上面的样板代码中,我们引用了我们的主要JavaScript文件app.js
和Pusher客户端JavaScript库。 我们还有一个script标记,用于将成员行的模板放置在成员列表中。 另外,我们有两个空的div标签,其ID为me
和membersList
用于包含已登录的成员名称和信息以及所有其他成员及其状态的列表。
步骤3:Style.css (Step 3: Style.css)
Important to note that we will be showing the signup form for the first time and the MembersList
and Logout
button will be hidden by default initially. Please create a new file called style.css
and add the following CSS to it:
需要注意的重要一点是,我们将首次显示注册表单,默认情况下, MembersList
和Logout
按钮将默认为隐藏。 请创建一个名为style.css
的新文件,并向其中添加以下CSS:
Please try to open the URL http://localhost:9000 in your browser and the application will load with the basic register or login form with username and status. The output will look like the screenshot below:
请尝试在浏览器中打开URL http:// localhost:9000 ,该应用程序将加载基本注册名或具有用户名和状态的登录表单。 输出将类似于以下屏幕截图:
步骤4:添加app.js基本代码 (Step 4: Add app.js basic code)
Now we will add our JavaScript code to have basic utility elements inside a self-invoking function to create a private scope for our app variables. We do not want to pollute JavaScript’s global scope.
现在,我们将添加JavaScript代码,以在自调用函数中包含基本实用程序元素,从而为我们的应用程序变量创建私有范围。 我们不想污染JavaScript的全局范围。
In the above code, we have referenced all the important variables we will be requiring. We will also initialize the Pusher library using new Pusher
and passing the API key as the first argument. The second argument contains an optional config object in which we will add the key authEndpoint
with the custom node API route /usersystem/auth
and also add the key encrypted
setting it to value true
.
在上面的代码中,我们已经引用了所有需要的重要变量。 我们还将使用new Pusher
初始化Pusher库,并将API密钥作为第一个参数传递。 第二个参数包含一个可选的config对象,我们将在其中添加具有自定义节点API路由/usersystem/auth
的密钥authEndpoint
,还添加将其设置为true
encrypted
密钥。
We will create a couple of generic functions to show or hide an element passing its unique id. We have also added a common method named ajax
to make AJAX requests using XMLHttp object in Vanilla JavaScript.
我们将创建几个通用函数来显示或隐藏通过其唯一ID的元素。 我们还添加了一个名为ajax
的通用方法,以使用Vanilla JavaScript中的XMLHttp对象发出AJAX请求。
At the load of the page we make an AJAX request to check if the user is logged in or not. If the user is logged in, we will directly use the Pusher instance to subscribe the user to a presence channel named presence-whatsup-members
. You can have this as the unique chat room or app location where you want to report/track the online members.
在页面加载时,我们发出AJAX请求以检查用户是否已登录。 如果用户已登录,我们将直接使用Pusher实例将用户订阅到一个名为presence-whatsup-members
的状态通道。 您可以将其作为要报告/跟踪在线成员的唯一聊天室或应用程序位置。
We have also written a method above to addNewMember
using an AJAX request to the register
API route we have built in Node.js. We will be passing the name and initial status entered into the form.
上面我们还编写了一种方法,该方法使用AJAX请求将addNewMember
到我们在Node.js中构建的register
API路由。 我们将在表单中输入名称和初始状态。
We also have a method to update the user view state based on the logged-in status. This method does nothing but update the visibility of the members list, logout button, and signup form. We have used a bindChannelEvents
method when the user is logged in, which we will be implementing later in the blog post.
我们还提供了一种基于登录状态更新用户视图状态的方法。 此方法除了更新成员列表,注销按钮和注册表单的可见性外,什么也不做。 用户登录时,我们已使用bindChannelEvents
方法,稍后将在博客文章中实现该方法。
Please add the following CSS in style.css
file to display the me
element appropriately with the username and the status of the logged-in user.
请在style.css
文件中添加以下CSS,以正确显示me
元素以及用户名和登录用户的状态。
步骤5:添加代码以呈现成员列表和bindChannelEvents (Step 5: Add code to render the members list and bindChannelEvents)
Now, after subscribing to the channel, we need to bind certain events so that we can know whenever a new member is added to the channel or removed from it. We will also bind to a custom event to know whenever someone updates their status.
现在,在订阅频道之后,我们需要绑定某些事件,以便我们可以知道何时有新成员添加到频道或从频道中删除。 我们还将绑定到自定义事件,以在有人更新状态时知道。
Add the following code to the app.js
file:
将以下代码添加到app.js
文件:
In the above bindChannelEvents
method, we use the channel.bind
method to bind event handlers for 3 internal events —usher:subscription_succeeded
, pusher:member_added
, pusher:member_removed
and 1 custom event —client-status-update
.
在上面的bindChannelEvents
方法中,我们使用channel.bind
方法绑定3个内部事件的事件处理程序— pusher:member_added
usher:subscription_succeeded
, pusher:member_added
, pusher:member_removed
和1个自定义事件client-status-update
。
Now we will add the JavaScript code to render the list of members. It is important to know that the object which I returned from the .subscribe
method has a property called members
, which can be used to know the information about the logged-in user referred by the key me
and other members by key members
. Add the following code to app.js
file:
现在,我们将添加JavaScript代码以呈现成员列表。 要知道,这是我从返回的对象是很重要的.subscribe
方法有一个名为属性members
,可以用来了解的信息登录的用户提到的关键me
和其他成员的关键members
。 将以下代码添加到app.js
文件:
We have added the event handler for new member add/remove event to re-render the members list so that it remains updated with the online members only. In order to show the members list, we need to add the following style into our file style.css
:
我们为新成员添加/删除事件添加了事件处理程序,以重新呈现成员列表,以便仅使用在线成员对其进行更新。 为了显示成员列表,我们需要在文件style.css
添加以下样式:
Now we will write the code to trigger a client event on our channel to notify all users about the status change of the logged in user. Add the following code to your app.js
file:
现在,我们将编写代码以触发我们的频道上的客户端事件,以通知所有用户有关已登录用户的状态更改。 将以下代码添加到您的app.js
文件中:
IMPORTANT: When we run this code in our browsers, update the status, and blur out of the status control, we will get an error in the JavaScript console for the Pusher library. To fix this, go to the console at Pusher.com website, go to settings, and enable sending events from clients directly.
重要说明 :当我们在浏览器中运行此代码,更新状态并模糊掉状态控件时,我们会在Pusher库JavaScript控制台中收到错误消息。 要解决此问题,请转到Pusher.com网站上的控制台,转到设置,然后启用直接从客户端发送事件的功能。
We can only send events from clients directly for Presence
or Private
channels. Link to the official documentation — https://Pusher.com/docs/client_api_guide/client_events#trigger-events
我们只能直接从客户发送Presence
或Private
频道的事件。 链接到官方文档-https://Pusher.com/docs/client_api_guide/client_events#trigger-events
结论 (Conclusion)
We have built an application which will display all the online members for a particular presence
channel and their status. If any of the online user updates their status, every user will be notified about the updated status.
我们已经构建了一个应用程序,该应用程序将显示特定presence
渠道及其状态的所有在线成员。 如果有任何在线用户更新其状态,则将通知每个用户有关更新状态。
This component or code can be used for developing a social networking section in most of the web apps these days. It is an important use case where the user needs to know about other available participants. For example: an online classroom app can see the other participants and the status can correspond to any question any participant wants to ask the presenter.
如今,此组件或代码可用于在大多数Web应用程序中开发社交网络部分。 这是一个重要的用例,其中用户需要了解其他可用的参与者。 例如:一个在线教室应用程序可以看到其他参与者,并且状态可以对应于任何参与者想要向演示者提问的任何问题。
We have just used Node.js and Vanilla JavaScript to implement the above functionality. You can use the JavaScript for front-end code with any popular framework like React or Angular. The back-end can also be Java or Ruby. Please refer to the Pusher docs for more information on this.
我们刚刚使用Node.js和Vanilla JavaScript来实现上述功能。 您可以将JavaScript用于前端代码以及任何流行的框架,例如React或Angular 。 后端也可以是Java或Ruby 。 请参考Pusher文档以获取更多信息。
This blog post was originally published on Pusher’s blog.
该博客文章最初发布在Pusher的博客上 。
ios pusher使用