ios pusher使用
by Rahat Khanna
通过拉哈特·汉娜
如何使用JavaScript和Pusher构建实时评论功能 (How to build a Live Comment feature using JavaScript and Pusher)
These days “Social” has become the buzzword and we all want our apps to be the center of these amazing social conversations. Comments on a post, video, update or any feature of your new app is a great way to add fun and enriching social conversations to your App.
如今,“社交”已成为流行语,我们都希望我们的应用成为这些令人惊叹的社交对话的中心。 对您的新应用的帖子,视频,更新或任何功能进行评论是一种为您的应用添加乐趣并丰富社交对话的好方法。
If these conversations can be realtime, then it’s even better. So in this article we will be discussing how we can create a realtime comment feature for our web apps using Pusher with Vanilla JavaScript on the front-end and Node.js on the back-end.
如果这些对话可以实时进行,那就更好了。 因此,在本文中,我们将讨论如何在前端使用Vanilla JavaScript,在后端使用Node.js的 Pusher为Web应用程序创建实时评论功能。
We will call this realtime comment system Flash Comments, which can be re-used for multiple posts/features in your app and can generate amazing conversations in real time. Only basic HTML, CSS and JavaScript knowledge is required to follow through this blog post.
我们将这种实时评论系统称为Flash Comments ,可以将其重新用于您应用中的多个帖子/功能,并可以实时生成令人惊叹的对话。 仅需要基本HTML,CSS和JavaScript知识即可阅读本博文。
Our app will look something like this:
我们的应用程序将如下所示:
栏目 (Sections)
- Brief Introduction to Pusher 推送器简介
- Signing Up with Pusher 使用Pusher进行注册
- Node.js and Express App for exposing a Comment Creation API and triggering a Pusher Event Node.js和Express App,用于公开注释创建API和触发Pusher事件
- Front End using Vanilla JavaScript subscribing to Channel 前端使用Vanilla JavaScript订阅频道
** Skip the first two sections, if you have already signed up with Pusher.
**如果您已经注册了Pusher,请跳过前两个部分。
推送器简介 (Brief Introduction to Pusher)
Pusher is an amazing 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 wide variety of software development kits (SDKs).
Pusher是一个了不起的平台,它抽象了使用WebSockets或Long Polling自己实现实时系统的复杂性。 我们可以使用Pusher立即将实时功能添加到我们现有的Web应用程序中,因为它支持多种软件开发工具包(SDK)。
Integration kits are available for 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 picture below. You will have to fill in some information about your project and also the front-end library or back-end language you will be building your app with. You also have an option to select the cluster of Pusher based on your users location distribution, I have chosen ap2 (Mumbai, India)
as I may be building an app for the India region.
您可以在推创建一个免费帐户这里 。 首次注册并登录后,将要求您创建一个新应用,如下图所示。 您将必须填写有关项目的一些信息,以及用于构建应用程序的前端库或后端语言。 您还可以根据您的用户位置分布选择Pusher群集,我选择了ap2 (Mumbai, India)
因为我可能正在为印度地区构建应用程序。
For this particular article, we will be selecting JavaScript for the front-end and Node.js for the back-end as seen in the picture 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 App)
You can create a new folder named flash-comments
and run the following command at the root of the folder:
您可以创建一个名为flash-comments
的新文件夹,并在该文件夹的根目录下运行以下命令:
It will ask you bunch of information regarding the app and it will create a new package.json
file inside your folder.
它将询问您有关该应用程序的大量信息,并将在您的文件夹中创建一个新的package.json
文件。
We will be using the fairly simple and popular Express framework in Node.js. Now, we will install the important packages that will be used in our minimal Express app.
我们将在Node.js中使用相当简单和流行的Express框架。 现在,我们将安装将在最小的Express应用程序中使用的重要软件包。
After installing all required npm
modules, now we will create an entry point file for our Node.js app as server.js
inside the root folder. Add the following basic code for a basic HTTP Server to be run using port 9000
.
安装所有必需的npm
模块之后,现在我们将在根文件夹内为Node.js应用程序创建一个入口点文件,作为server.js
。 为要使用端口9000
运行的基本HTTP Server添加以下基本代码。
Pusher has an open source NPM module for the 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
模块:
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 put random keys. You will have to obtain it 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. This API will expose the route /comment
with HTTP POST
method and will expect an object for comment with the properties name
, email
and comment
. Add the following code to your server.js
file before the app.listen
part.
您将必须使用特定于您自己的应用程序的值替换appId
, key
和secret
。 之后,我们将为新的API编写代码,这些代码将用于创建新的注释。 该API将使用HTTP POST
方法公开路由/comment
,并期望使用属性name
, email
和comment
进行注释的对象。 在app.listen
部分之前,将以下代码添加到server.js
文件中。
In the above code, we have extracted the data from req.body
into a newComment
object and then used it to call the trigger
method on the Pusher
instance.
在上面的代码中,我们已经将数据从req.body
提取到newComment
对象中,然后使用它在Pusher
实例上调用trigger
方法。
重要的推杆概念 (Important Pusher Concepts)
渠道 (Channel)
In Pusher, we have a conceptual grouping called “channels” and it provides the basic way to filter data in Pusher. A channel can represent many entities in a real world application. For example: In our comments app, a channel can be comments for a specific Article, video, blog post, photo, or live streaming of an event.
在Pusher中,我们有一个称为“渠道”的概念性分组,它提供了在Pusher中过滤数据的基本方法。 通道可以代表现实应用程序中的许多实体。 例如:在我们的评论应用程序中,频道可以是特定文章,视频,博客文章,照片或事件的实时流的评论。
We would create a new unique channel id for each of these entities to uniquely identify or group data like comments associated with any one of these. Two unique live streaming videos should also have separate channels so that we can show the respective live comments stream on their respective pages.
我们将为这些实体中的每个实体创建一个新的唯一通道ID,以唯一地标识或分组数据,例如与这些实体中的任何一个相关的评论。 两个独特的实时流媒体视频也应具有单独的频道,以便我们可以在各自的页面上显示各自的实时评论流。
So we will create a new unique channel for each entity with their unique id. For example a YouTube video comments channel can be named comments-youtube-234
.
因此,我们将为每个具有唯一ID的实体创建一个新的唯一渠道。 例如,YouTube视频评论频道可以命名为comments-youtube-234
。
There are three types of channel
频道有三种
Public Channel — can be subscribed by anyone who knows the name of the channel.
公共频道 -任何知道频道名称的人都可以订阅。
Private Channel — channel which can be subscribed by authorized users only. If the channel name has a
private-
prefix, it will be regarded as a private channel.专用频道 -只能由授权用户订阅的频道。 如果通道名称有一个
private-
的前缀,这将被视为一个专用通道。Presence Channel — this is a special channel type similar to private as only authorized users can subscribe, where the subscribers list is also maintained and notified to other users also. Channel name should have a prefix
presence-
出席频道 -这是一种特殊的频道类型,类似于专用频道,因为只有授权用户才能订阅,订阅者列表也得到维护,并也通知其他用户。 频道名称应该有一个前缀
presence-
We will use a public channel in our blog post which we are naming as flash-comments but you should ideally use a private channel for commenting systems with unique name for each entity you want to enable commenting feature.
我们将在博客文章中使用一个公共频道,我们将其命名为快速评论,但是理想情况下,您应该对要启用评论功能的每个实体使用专用频道的评论系统使用唯一的名称。
事件 (Event)
Now, the real data in pusher is transmitted through events which is the primary way of packaging messages. An event can be triggered by a back-end or even client in special cases for any particular channel. A channel is required to ensure that your message reaches the intended recipient.
现在,推送程序中的实际数据通过事件进行传输,这是打包消息的主要方式。 在特殊情况下,后端或什至客户端可以针对任何特定通道触发事件。 需要一个渠道来确保您的邮件到达预期的收件人。
We give a unique name to each event so that we can setup handlers for receiving and processing these event messages at each of our client end who has subscribed to any channel.
我们为每个事件指定一个唯一的名称,以便我们可以在已订阅任何频道的每个客户端上设置用于接收和处理这些事件消息的处理程序。
推杆触发方式 (Pusher Trigger Method)
Now we will understand our server side code for sending an event to the pusher channel flash-comments
.
现在,我们将了解用于将事件发送到推送程序通道flash-comments
服务器端代码。
We are using the .trigger(channel-name,event-name, payload)
to send an event from the server whenever the POST
API is called for creating a new comment. For the simplicity of this article, we will not use any database to save and persist the comments but in a production system. You would be required to store a comment corresponding to a unique entity id like a YouTube Video ID or a Blog Post ID.
每当调用POST
API创建新注释时,我们就使用.trigger(channel-name,event-name, payload)
从服务器发送事件。 为了简化本文,我们将不在生产系统中使用任何数据库来保存和保留注释。 您将需要存储与唯一实体ID(例如YouTube视频ID或博客文章ID)相对应的评论。
Now, we can run our server using node server
command. Our web service will be accessible on the URL http://localhost:9000/comment
.We can write a POST
request using any chrome extension like Postman or even curl to test if it returns { "created":"true" }
.
现在,我们可以使用node server
命令运行node server
。 我们的Web服务将可通过URL http://localhost:9000/comment
。我们可以使用任何Chrome扩展名(例如Postman)甚至curl编写POST
请求,以测试其是否返回{ "created":"true" }
。
The curl command to test your POST
API will be as follows:
curl命令用于测试POST
API,如下所示:
使用Vanilla JavaScript的前端 (Front-End using Vanilla JavaScript)
Now, we will be writing the most crucial part, the front-end code using Vanilla JavaScript. In the front-end code we will be developing a comments box section which would have following two features:
现在,我们将使用Vanilla JavaScript编写最关键的部分,即前端代码。 在前端代码中,我们将开发一个注释框部分,其中将具有以下两个功能:
Display all the Live Comments added to the channel with a smooth animation
以平滑的动画显示添加到频道的所有实时评论
Add new comment to the live comments by hitting the
POST
API we have just created通过点击我们刚刚创建的
POST
API, 将新评论添加到实时评论中
步骤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 content like video or blog post can be put and also the section which will contain our Flash Comments
box.
我们将添加一些基本的样板代码来设置Web应用程序的基本结构,例如Header
,以及可以放置视频或博客文章等内容的Sections
以及将包含Flash Comments
框的部分。
步骤3:建立style.css档案 (Step 3: Create style.css file)
Now we will also create a style.css
file to contain the important CSS code for styling our web app and the flash comments
component. We will add basic styles to render our skeleton.
现在,我们还将创建一个style.css
文件,其中包含用于样式化Web应用程序和flash comments
组件的重要CSS代码。 我们将添加基本样式来渲染我们的骨架。
步骤4:添加pusher.js库并创建app.js (Step 4: Add the pusher.js Library and create app.js)
Now we will add the pusher.js Library available on its CDN to use it to integrate with the Pusher system using plain JavaScript code. Please add the following script tag at the end of the body before its closing tag:
现在,我们将在CDN上添加pusher.js库,以使用纯JavaScript代码将其与Pusher系统集成。 请在主体结尾处的结束标记之前添加以下脚本标记:
Also, create a new app.js
file where we will be writing all our code and also import the same in our index.html
file after the script tag to import pusher.js
file.
另外,创建一个新的app.js
文件,在该文件中我们将编写所有代码,并在脚本标记之后的index.html
文件中导入相同的代码以导入pusher.js
文件。
In our file app.js
now, we will write code to initialize the Pusher instance using the unique client API key we have got from the Pusher dashboard. We will also pass an object specifying the cluster and setting the flag encrypted to true so that all messaging and communication is encrypted. We will also use the pusher.subscribe('channel-name')
to listen to all events for a specific channel.
现在,在文件app.js
,我们将使用从Pusher仪表板获取的唯一客户端API密钥编写代码以初始化Pusher实例。 我们还将传递一个对象,该对象指定集群并将标记加密设置为true,以便所有消息传递和通信都被加密。 我们还将使用pusher.subscribe('channel-name')
侦听特定频道的所有事件。
We will create a JavaScript IIFE (Immediately Invoking Functions) to create a private scope so that we do not pollute the global scope. Please add the following code to app.js
file:
我们将创建一个JavaScript IIFE(立即调用函数)来创建一个私有范围,这样我们就不会污染全局范围。 请将以下代码添加到app.js
文件:
步骤5:创建用于添加新评论的表单 (Step 5: Creating Form for adding new comment)
Now, we will create the form controls for letting the user input their name, email and comment text for creating a new comment using our Node.js API and Pusher. We will add the following HTML code inside the existing form tag to create the form:
现在,我们将创建表单控件,以允许用户输入其名称,电子邮件和评论文本,以便使用我们的Node.js API和Pusher创建新评论。 我们将在现有的表单标签内添加以下HTML代码以创建表单:
In the form code above, we have used HTML5 validations like required
and type=email
which would not allow user to keep these fields blank or submit an invalid email. These validations will automatically work in most browsers which support HTML5 form validations.
在上面的表单代码中,我们使用了HTML5验证(例如r equired
和type=email
,这些验证不允许用户将这些字段保留为空白或提交无效的电子邮件。 这些验证将在大多数支持HTML5表单验证的浏览器中自动运行。
Also, we will be adding the following CSS to style the form:
另外,我们将添加以下CSS来设置表单样式:
After building the visual form, now we need to attach an event handler to the Submit
event of the form. We will do that using the following code in the app.js
file, probably at the top after the var
declarations:
构建可视表单之后,现在我们需要将事件处理程序附加到表单的Submit
事件。 我们将在app.js
文件中使用以下代码(可能在var
声明之后的顶部)进行此操作:
Now, we will write the code for implementation of the handler addNewComment
with the following code:
现在,我们将使用以下代码编写用于实现处理程序addNewComment
的代码:
We are using native XHR request to make an AJAX request to the Node API. You can use either jQuery AJAX or any framework-specific ajax
method in your app. Now if we run our application, then fill the form and submit it, we will see a Success: { created: true }
message in our browser developer tools console.
我们正在使用本机XHR请求向Node API发出AJAX请求。 您可以在应用程序中使用jQuery AJAX或任何特定于框架的ajax
方法。 现在,如果我们运行应用程序,然后填写表格并提交,我们将在浏览器开发人员工具控制台中看到一条Success: { created: true }
消息Success: { created: true }
。
Also, we can see the Pusher Dashboard to see the stats about Event Messages sent for any channel.
另外,我们可以看到Pusher Dashboard,以查看有关为任何频道发送的事件消息的统计信息。
步骤6:显示为此频道收到的评论列表 (Step 6: Display List of Comments Received for this Channel)
Now, we will bind to the new_comment
event on this channel flash-comments
so that we can receive any message about new comment creation done from any client in realtime, and we can display all those comments.
现在,我们将在此频道flash-comments
new_comment
上绑定到new_comment
事件,以便我们可以实时接收来自任何客户端的有关创建新评论的任何消息,并可以显示所有这些评论。
We will first add a template for a new comment in our index.html
file inside the div tag with id="comments-list"
.
我们将首先在div标签中的id="comments-list"
index.html
文件中为新注释添加模板。
Now, we will write the JavaScript code to bind to the new_comment event on the pusher channel instance we have subscribed. Whenever the new_comment
event will be fired, we will take the template innerHTML content and replace the placeholders {{name}}, {{email}} & {{comment}}
with the data passed along with the event and append them to the comments-list
div element.
现在,我们将编写JavaScript代码以绑定到已订阅的pusher通道实例上的new_comment事件。 每当将触发new_comment
事件时,我们都会获取模板innerHTML内容,并用与事件一起传递的数据替换占位符{{name}}, {{email}} & {{comment}}
并将其附加到comments-list
div元素。
Using the above code, a new div tag representing the new comment will automatically be created and appended to the comments-list
container.
使用上面的代码,将自动创建一个代表新评论的div标签,并将其附加到comments-list
容器中。
We will now add the following CSS to nicely display the list of comments and also animate whenever a new comment appears on the list:
现在,我们将添加以下CSS,以很好地显示评论列表,并在列表上出现新评论时也进行动画处理:
Now, you can run the app we have built, either in two different browsers or one in normal browser and the other in incognito window, and add multiple comments. We can see that the live comments will be added in realtime with a smooth animation.
现在,您可以在两个不同的浏览器中运行一个构建的应用程序,或者在普通浏览器中运行一个应用程序,在隐身窗口中运行另一个应用程序,然后添加多个注释。 我们可以看到实时注释将通过平滑的动画实时添加。
The complete code for this tutorial is available on GitHub.
结论 (Conclusion)
We have built a nice web app with live comment feature using Pusher, Node.js and Vanilla JavaScript. We can use this component with any of our applications and enable live comments for variety of social entities like Videos, Blog Post, Polls, Articles and live streams.
我们使用Pusher,Node.js和Vanilla JavaScript构建了一个具有实时注释功能的精美Web应用程序。 我们可以在任何应用程序中使用此组件,并为各种社交实体(例如视频,博客文章,民意调查,文章和实时流)启用实时评论。
We have used the Node.js server to create a REST API to get a new comment and then trigger a Pusher event on a specific channel. For any real world application, we can take a unique id for each entity and use a unique channel name for any entity. In a production scenario we can also store the comments in a persistent storage and then later retrieve them.
我们已经使用Node.js服务器创建REST API来获取新注释,然后在特定频道上触发Pusher事件。 对于任何实际应用,我们可以为每个实体使用唯一的ID,并为任何实体使用唯一的通道名称。 在生产方案中,我们还可以将评论存储在持久性存储中,然后再检索它们。
We have also created a Front-End app, which will connect to the Pusher API using the pusher.js library. We have created a form to hit the Node API which will trigger the new_comment
event. Comments are displayed in realtime with an animation using the bind method on the channel instance.
我们还创建了一个前端应用程序,它将使用pusher.js库连接到Pusher API。 我们创建了一个表单来命中Node API,这将触发new_comment
事件。 使用通道实例上的bind方法,注释与动画一起实时显示。
This article was originally published on Pusher’s blog.
本文最初发布在Pusher的博客上 。
ios pusher使用