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.
在此處找到指向 Github存儲庫的鏈接以供參考。
推桿簡介 (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的博客上 。
翻譯自: https://www.freecodecamp.org/news/how-to-update-a-users-status-in-realtime-using-javascript-and-pusher-2cae8f4aaafa/
ios pusher使用