使用Chatkit構建Node.js命令行聊天應用程序

by Hugo

雨果

使用Chatkit構建Node.js命令行聊天應用程序 (Build a Node.js command-line chat application with Chatkit)

Building chat in your app can be pretty complex. Yet, with Chatkit, implementing fully-featured chat is nothing but a few lines of code.

在您的應用中建立聊天可能非常復雜。 但是,使用Chatkit ,實現功能齊全的聊天只不過是幾行代碼。

In this tutorial, I’ll walk you through how to build a command-line chat, like this:

在本教程中,我將指導您如何建立命令行聊天,如下所示:

The complete code can be found on GitHub.

完整的代碼可以在GitHub上找到 。

什么是Chatkit? (What is Chatkit?)

You might be wondering, “what is Chatkit?”

您可能會想,“什么是Chatkit?”

In a nutshell, Chatkit is an API to help you build chat functionality in your app. Functionality like:

簡而言之,Chatkit是一個API,可幫助您在應用程序中構建聊天功能。 功能類似:

  • Rooms

    房間數
  • Online presence

    在線存在
  • Typing indicators

    打字指標
  • Read indicators (unread message count, read receipts)

    閱讀指示器(未讀郵件數,已讀回執)
  • Rich media messages

    富媒體消息
  • And more

    和更多

Additionally, Chatkit handles tricky details that come up when building real-time chat like reliability, and scale.

此外,Chatkit處理構建實時聊天時出現的棘手細節,例如可靠性和規模。

To me, using Chatkit means not having to deal with rolling a web socket server, managing infrastructure for it, and dealing with managing chat at scale!

對我來說,使用Chatkit意味著不必處理滾動Web套接字服務器,管理該服務器的基礎結構以及處理大規模聊天的問題!

In this tutorial, we’ll only touch the surface of what Chatkit can do. To give you an idea of what you can build, check out this open source Slack clone, powered by Chatkit:

在本教程中,我們僅涉及Chatkit可以做的事情。 為了讓您大致了解可以構建的內容,請查看由Chatkit支持的開源Slack克隆:

Pretty neat, right?

很整潔吧?

創建一個Chatkit實例 (Create a Chatkit instance)

Before diving into the tutorial, you should setup a Chatkit instance. It only takes a second.

在開始學習本教程之前,您應該設置一個Chatkit實例。 只需要一秒鐘。

To create one, head to pusher.com/chatkit and click Sign Up. Within the dashboard, beneath “Chatkit”, hit Create new + then enter a name for the instance. I called mine “My Awesome Chatkit App!”:

要創建一個,請訪問pusher.com/chatkit并單擊“ 注冊” 。 在儀表板內的“ Chatkit”下,單擊“ 創建新+ ”,然后輸入實例的名稱。 我稱我為“我的超贊聊天工具應用!”:

Within the Keys tab, take note of your Instance Locator and Secret Key. We’ll need these in a moment.

在“ 密鑰”選項卡中,記下您的Instance LocatorSecret Key 。 我們稍后將需要這些。

創建聊天室 (Create a Chatkit room)

Chatkit enables us to create public or private chat rooms, and even supports one-to-one chat.

Chatkit使我們能夠創建公共或私人聊天室,甚至支持一對一聊天。

Normally, you’d create rooms dynamically — for example, when an end user creates a new room—but in this tutorial we’ll the Inspector to create one manually:

通常,您會動態創建房間(例如,當最終用戶創建新房間時),但是在本教程中,我們將由檢查員手動創建一個房間:

創建身份驗證服務器 (Create an authentication server)

Authentication is the action of proving a user is who they say they are. Normally, this involves a password.

身份驗證是證明用戶就是他們所說的身份的行為。 通常,這涉及一個密碼。

In this tutorial, we won’t authenticate users —we won’t ask them for a password — but we’ll still need to write an /authenticate route that returns a Chatkit token.

在本教程中,我們不會對用戶進行身份驗證-我們不會要求他們提供密碼-但我們仍然需要編寫/authenticate路由來返回Chatkit令牌 。

Additionally, we’ll need to define a route called /users that creates a Chatkit user.

此外,我們需要定義一個名為/users的路由,以創建一個Chatkit用戶。

To do this, create a new folder, I called mine terminal-chat. Then, install @pusher-chatkit-server , express, and some Express middleware:

為此,請創建一個新文件夾,我稱為mine terminal-chat 。 然后,安裝@pusher-chatkit-serverexpress和一些Express中間件:

mkdir terminal-chat
cd terminal-chat
npm init -y
npm install --save @pusher/chatkit-server npm install --save express npm install --save body-parser cors

Then, create a new file called server.js and paste in the following code:

然后,創建一個名為server.js的新文件,并粘貼以下代碼:

Remember to replace YOUR_INSTANCE_LOCATOR and YOUR_CHATKIT_KEY with your own.

請記住用自己的替換YOUR_INSTANCE_LOCATORYOUR_CHATKIT_KEY

設置我們的客戶 (Setup our client)

Now we have a server and a Chatkit instance, we can start building the command-line client.

現在我們有了服務器和Chatkit實例,我們可以開始構建命令行客戶端了。

In the same project, install @pusher/chatkit and jsdom:

在同一項目中,安裝@pusher/chatkitjsdom

npm install --save @pusher/chatkitnpm install --save jsdom

To be clear, in the previous step, we installed the Chatkit server SDK (@pusher/chatkit-server) and here, we install the client Chatkit SDK (@pusher/chatkit-client). We also installed jsdom, but more on that in a moment.

為了清楚起見,在上一步中,我們安裝了Chatkit 服務器 SDK( @pusher/chatkit-server ),在這里,我們安裝了客戶端 Chatkit SDK( @pusher/chatkit-client )。 我們還安裝了jsdom ,但jsdom更多介紹。

In a new file called client.js, paste the following:

在名為client.js的新文件中,粘貼以下內容:

Starting at the top, we first import ChatManager and TokenProvider from @pusher/chatkit. We’ll reference these soon.

從頂部開始,我們首先從@pusher/chatkit導入ChatManagerTokenProvider 。 我們將盡快參考這些內容。

We also import jsdom, the dependency I mentioned earlier.

我們還導入了前面提到的jsdom

In a nutshell, @pusher/chatkit-client works in the browser but not in Node. In a function called makeChatkitNodeCompatible, we use jsdom to “trick” Chatkit into thinking it’s running in the browser ?. This is a temporary workaround, but it works perfectly.

簡而言之, @pusher/chatkit-client在瀏覽器中有效,而在Node中不起作用。 在一個名為makeChatkitNodeCompatible的函數中,我們使用jsdom來“欺騙” Chatkit,使其認為它正在瀏覽器中運行? 這是在應急解決方法上,但它可以完美運行。

At the bottom of the module, we define an async function called main, which enables us to use await when calling asynchronous functions.

在模塊的底部,我們定義了一個名為mainasync函數,該函數使我們能夠在調用異步函數時使用await

If await is a new concept to you, here’s a great introduction.

如果對您來說await是一個新概念,這是一個很棒的介紹 。

提示用戶輸入用戶名 (Prompt the user for their username)

Before we can allow a user to join a room, we need prompt them for their name. To do this, we can use prompt.

在允許用戶加入房間之前,我們需要提示他們輸入名稱。 為此,我們可以使用prompt.

First, install prompt:

首先,安裝prompt

npm install --save prompt

And then, import it:

然后導入:

Then, update our main function:

然后,更新我們的主要功能:

Now, if we run the app with the command node client.js, we should have our prompt:

現在,如果使用命令node client.js運行該應用程序,則應顯示提示:

Woo ?!

??!

創建一個用戶 (Create a user)

Before connecting to Chatkit, we must first create a Chatkit user via the server we wrote earlier.

連接到Chatkit之前,我們必須首先通過我們先前編寫的服務器創建一個Chatkit用戶。

To do this, we’ll send a request to the /users route using axios, which is a HTTP client:

為此,我們將使用axios將請求發送到/users路由, axios是HTTP客戶端:

npm install --save axios

After installing axios, import it:

安裝axios ,將其導入:

Then, define a function called createUser:

然后,定義一個名為createUser的函數:

We can now call this function with the prompted username:

現在,我們可以使用提示的用戶名調用此函數:

Let’s test this out.

讓我們測試一下。

Open two terminal windows. In one, start the server with node server.js and in the other, run the client with node client.js. If all is well, you should be prompted for a username, and you’ll see User created: <username> in the server output.

打開兩個終端窗口。 一種是使用node server.js啟動服務器,另一種是使用node client.js運行客戶node client.js 。 如果一切正常, 則系統將提示您輸入用戶名,并且服務器輸出User created: <userna me>。

If you see an error along the lines of Failed to create a user, connect ECONNREFUSED then your server might not be running, so double check that.

如果Failed to create a user, connect ECONNREFUSED的行中看到錯誤Failed to create a user, connect ECONNREFUSED則您的服務器可能未運行,因此請仔細檢查。

設置Chatkit SDK (Setup the Chatkit SDK)

At this point, we have a username and the ability to create a user. Next, we’ll want to connect to Chatkit as that user.

至此,我們有了用戶名和創建用戶的能力。 接下來,我們要以該用戶身份連接到Chatkit。

To do this, beneath the call you just made to createUser, paste the following:

為此,在您剛剛對createUser進行的調用下面,粘貼以下內容:

Again, remember to replace your YOUR_INSTANCE_LOCATOR with the Instance Locator you noted earlier.

同樣,請記住將您的YOUR_INSTANCE_LOCATOR替換為您之前提到的實例定位器

This code initialises Chatkit then connects to the service, returning the currentUser. Note how we provide a TokenProvider which points to our authentication server.

此代碼初始化Chatkit,然后連接到服務,并返回currentUser 。 請注意,我們如何提供指向我們的身份驗證服務器TokenProvider

上市房 (Listing rooms)

Now we have an authenticated user, we can show them a list of rooms they can join.

現在我們有了一個經過身份驗證的用戶,我們可以向他們顯示他們可以加入的房間的列表。

To do this, we should update the main function in client.js to fetch joinable rooms (getJoinableRooms), and list them alongside the rooms a user has already joined (user.rooms):

要做到這一點,我們應該更新的主要功能client.js獲取可連接室( getJoinableRooms ),并列出他們旁邊的房間用戶已經加入( user.rooms ):

The ... syntax there is called destructuring, and it provides a succinct way to merge two or more arrays.

那里的...語法稱為destructuring ,它提供了合并兩個或更多數組的簡潔方法。

Running node client.js should now print out a list of rooms:

運行node client.js現在應該打印出房間列表:

You’ll probably just see one room to start with. To create additional rooms, go back to the Inspector or use the the createRoom function.

您可能只會看到一個房間開始。 要創建其他房間,請返回檢查器或使用createRoom功能。

訂閱房間 (Subscribe to a room)

Next, we should prompt the user to pick a room, with this code:

接下來,我們應使用以下代碼提示用戶選擇房間:

One cool thing about prompt is that you can create validation rules. Above, we create one to make sure the user’s input is between 0 and the number of joinable rooms.

關于prompt一件很酷的事情是,您可以創建驗證規則。 在上面,我們創建一個以確保用戶輸入的值在0到可連接房間的數量之間。

Once we have the user’s room choice, we can set that as the room and subscribe to the room:

選擇了用戶的房間后,我們可以將其設置為room并訂閱該房間:

Upon subscribing, we add a onNewMessage hook.

訂閱后,我們添加了onNewMessage 鉤子

You can think of a hook as a function that is called whenever an event occurs. In this case it’s when a new message is received.

您可以將鉤子視為事件發生時調用的函數。 在這種情況下,就是收到新消息的時候。

onNewMessage will be called in real-time whenever a new message is sent by “a user”. When I say “a user”, that includes the current user, so within the function we only print the message if it was sent by someone else.

每當“用戶”發送新消息時,就會實時調用onNewMessage 。 當我說“用戶”時,其中包括當前用戶,因此在此功能中,我們僅在消息是由其他人發送的情況下打印消息。

通過用戶輸入發送消息 (Send messages from user input)

Being able to receive messages isn’t much use if we can’t also send messages now, is it?

如果我們現在也不能發送消息,那么能夠接收消息的用處不大,不是嗎?

Fortunately, sending a message is but one line of code with Chatkit.

幸運的是,使用Chatkit發送消息只是一行代碼。

First, install readline to read input from the user:

首先,安裝readline以讀取用戶的輸入:

npm install --save readline

Then, import it:

然后,將其導入:

Finally, reference it below:

最后,在下面引用它:

If you run two instances of the client, you should be able to send and receive messages:

如果運行客戶端的兩個實例,則應該能夠發送和接收消息:

添加一個加載微調器,讓它很有趣? (Add a loading spinner for a bit of fun ?)

As ever, sending data over the network might take a second or two. For a bit of fun, and to make our application feel faster, let’s add a nifty loading spinner:

與以往一樣,通過網絡發送數據可能需要一到兩秒鐘。 對于一點樂趣,并且使我們的應用程序的感覺速度更快,讓我們添加一個漂亮的加載微調:

First, install ora, a loading spinner module:

首先,安裝ora ,它是一個加載微調器模塊:

npm install --save ora

Then, in client.js,we can call start, succeed, etc. depending on the status of the command.

然后,在client.js ,我們可以根據命令的狀態調用startsucceed等。

Here’s the complete client.js file, with the new spinner-related code highlighted:

這是完整的client.js文件,其中突出顯示了與微調框相關的新代碼:

結論 (Conclusion)

Amazing, we’re done!

太神奇了,我們完成了!

To recap, you learned how to:

回顧一下,您學習了如何:

  • Prompt and authenticate the user

    提示并驗證用戶
  • Connect to Chatkit

    連接到聊天包
  • List the users available rooms

    列出用戶可用的房間
  • Join a room

    加入房間
  • Send and receive messages from a room

    在會議室發送和接收消息
  • And, for fun, add a loading spinner

    并且,為了娛樂,添加一個加載微調器

In this tutorial, we barely touched the surface of Chatkit. There’s so much more we could build, including:

在本教程中,我們幾乎沒有觸及Chatkit的表面。 我們可以建立更多的東西,包括:

  • Switch between rooms

    在房間之間切換
  • Create new rooms

    建立新房間
  • Show users offline/offline status

    顯示用戶離線/離線狀態
  • Show typing indicators

    顯示打字指示
  • Show read receipts

    顯示已讀回執

Want to learn how? Let me know in the comments and we’ll write part 2.

想學習如何? 在評論中讓我知道,我們將編寫第2部分。

Alex Booker created a video tutorial based on this article. Check it out!

Alex Booker根據本文創建了一個視頻教程。 看看這個!

翻譯自: https://www.freecodecamp.org/news/build-a-node-js-command-line-chat-application-with-chatkit-8d0c4546085e/

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/394062.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394062.shtml
英文地址,請注明出處:http://en.pswp.cn/news/394062.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

java 毫秒轉分鐘和秒_Java程序將毫秒轉換為分鐘和秒

Java程序將毫秒轉換為分鐘和秒在上面的程序中&#xff0c;您將學習如何在Java中將毫秒分別轉換為分鐘和秒。示例1&#xff1a;將毫秒分別轉換為分鐘和秒import java.util.concurrent.TimeUnit;public class Milliseconds {public static void main(String[] args) {long millis…

Andrew Ng機器學習之一 導論

監督學習與無監督學習 監督學習&#xff08;Supervised Learning) Ng的原文是&#xff1a; We gave the algorithm a data set that the "right answers" were given. 即給定了一個正確結果的集合供算法學習&#xff0c;強調了需要實現準備好正負樣本喂給機器。 無監…

leetcode994. 腐爛的橘子(bfs)

在給定的網格中&#xff0c;每個單元格可以有以下三個值之一&#xff1a; 值 0 代表空單元格&#xff1b; 值 1 代表新鮮橘子&#xff1b; 值 2 代表腐爛的橘子。 每分鐘&#xff0c;任何與腐爛的橘子&#xff08;在 4 個正方向上&#xff09;相鄰的新鮮橘子都會腐爛。 返回直…

ES6對象的擴展

1.屬性簡寫表示 2.方法簡寫表示 屬性與方法簡寫&#xff1a; 3.屬性名表達式 ES6允許字面量定義對象時&#xff0c;用方法二&#xff08;表達式&#xff09;作為對象的屬性名&#xff0c;即把表達式放在方括號內。 4.Object.is()比較兩個值是否嚴格相等 轉載于:https://www.cnb…

Spring Cloud項目MVN編譯 -- Non-resolvable import POM

最近利用閑余時間&#xff0c;打算搭建一套基于Spring Cloud G版的微服務架構(Spring boot 2.1.0)&#xff0c;一頓操作之后,IDEA也沒有提示什么錯誤,自認為微服務搭建完畢。啟動項目前&#xff0c;習慣性的Maven -clean了一下&#xff0c;我去&#xff0c;IDEA里面的Maven Pro…

datax底層原理_Datax 插件加載原理

Datax 插件加載原理插件類型Datax有好幾種類型的插件&#xff0c;每個插件都有不同的作用。reader&#xff0c; 讀插件。Reader就是屬于這種類型的writer&#xff0c; 寫插件。Writer就是屬于這種類型的transformer&#xff0c; 目前還未知handler&#xff0c; 主要用于任務執行…

mysql windows身份驗證_SQL Server 2005 怎么就不能用Windows身份驗證方式登錄呢?

SQL Server 2005 自從裝到我的電腦上始終無法使用Windows身份驗證的方式登錄,由于使用用戶名和密碼登錄還算順暢,所以一直忽略了這SQL Server 2005 自從裝到我的電腦上始終無法使用Windows身份驗證的方式登錄,由于使用用戶名和密碼登錄還算順暢,所以一直忽略了這個問題,直到又有…

JavaScript正則表達式快速簡單的指南

Interested in learning JavaScript? Get my ebook at jshandbook.com有興趣學習JavaScript嗎&#xff1f; 在jshandbook.com上獲取我的電子書 正則表達式簡介 (Introduction to Regular Expressions) A regular expression (also called regex for short) is a fast way to w…

leetcode104. 二叉樹的最大深度(dfs)

給定一個二叉樹&#xff0c;找出其最大深度。二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。說明: 葉子節點是指沒有子節點的節點。示例&#xff1a; 給定二叉樹 [3,9,20,null,null,15,7]&#xff0c;3/ \9 20/ \15 7 返回它的最大深度 3 。代碼 class Soluti…

[解讀REST] 3.基于網絡應用的架構

鏈接上文[解讀REST] 2.REST用來干什么的&#xff1f;&#xff0c;上文中解釋到什么是架構風格和應該以怎樣的視角來理解REST&#xff08;Web的架構風格&#xff09;。本篇來介紹一組自洽的術語&#xff0c;用它來描述和解釋軟件架構&#xff1b;以及列舉下對于基于網絡的應用來…

js判斷對象還是數組

1.對于Javascript 1.8.5&#xff08;ECMAScript 5&#xff09;&#xff0c;變量名字.isArray( )可以實現這個目的 var a[]; var b{}; Array.isArray(a);//true Array.isArray(b)//false 2.如果你只是用typeof來檢查該變量&#xff0c;不論是array還是object&#xff0c;都將返回…

mysql 除去列名打印_sql – 使用beeline時避免在列名中打印表名

在beeline中使用hive時使用簡單的select查詢我想在列名中返回沒有表名的表作為默認值.例數據CREATE TABLE IF NOT EXISTS employee ( eid int, name String,salary String, destination String)COMMENT Employee detailsROW FORMAT DELIMITEDFIELDS TERMINATED BY \tLINES TERM…

移動應用程序和網頁應用程序_如何開發感覺像本機移動應用程序的漸進式Web應用程序...

移動應用程序和網頁應用程序by Samuele Dassatti通過薩穆爾達薩蒂 如何開發感覺像本機移動應用程序的漸進式Web應用程序 (How you can develop Progressive Web Apps that feel like native mobile apps) I’m currently developing a Progressive Web App that will also ser…

leetcode1162. 地圖分析(bfs)

你現在手里有一份大小為 N x N 的「地圖」&#xff08;網格&#xff09; grid&#xff0c;上面的每個「區域」&#xff08;單元格&#xff09;都用 0 和 1 標記好了。其中 0 代表海洋&#xff0c;1 代表陸地&#xff0c;請你找出一個海洋區域&#xff0c;這個海洋區域到離它最近…

mysql修改root密碼的方法

在 Navicat for MySQL 下面直接執行 SET PASSWORD FOR rootlocalhost PASSWORD(newpass); 就可以 方法1&#xff1a; 用SET PASSWORD命令 mysql -u root mysql> SET PASSWORD FOR rootlocalhost PASSWORD(newpass); 方法2&#xff1a;用mysqladmin mysqladmin -u root …

android 上下偏差怎么寫_詳解 Android 熱更新升級如何突破底層結構差異?

知道了 native 替換方式兼容性問題的原因&#xff0c;我們是否有辦法尋求一種新的方式&#xff0c;不依賴于 ROM 底層方法結構的實現而達到替換效果呢&#xff1f;我們發現&#xff0c;這樣 native 層面替換思路&#xff0c;其實就是替換 ArtMethod 的所有成員。那么&#xff0…

Python3 Flask+nginx+Gunicorn部署(上)

前言&#xff1a;一般在本地運行flask項目通常是直接python3 文件名.py&#xff0c;然后打開&#xff1a;http://127.0.0.1:5000 查看代碼結果 這次主要是記錄flask在python3 環境結合nginx gunicorn在服務器上進行項目的部署 &#xff08;一&#xff09;運行環境&#xff1a;虛…

NOIP2011 鋪地毯

題目描述 為了準備一個獨特的頒獎典禮&#xff0c;組織者在會場的一片矩形區域&#xff08;可看做是平面直角坐標系的第一象限&#xff09;鋪上一些矩形地毯&#xff0c;一共有n張地毯&#xff0c;編號從 1 到n。現在將這些地毯按照編號從小到大的順序平行于坐標軸先后鋪設&…

java lock可重入_Java源碼解析之可重入鎖ReentrantLock

本文基于jdk1.8進行分析。ReentrantLock是一個可重入鎖&#xff0c;在ConcurrentHashMap中使用了ReentrantLock。首先看一下源碼中對ReentrantLock的介紹。如下圖。ReentrantLock是一個可重入的排他鎖&#xff0c;它和synchronized的方法和代碼有著相同的行為和語義&#xff0c…

matlab的qammod函數_基于-MATLAB下的16QAM仿真.doc

1.課程設計目的隨著現代通信技術的發展&#xff0c;特別是移動通信技術高速發展&#xff0c;頻帶利用率問題越來越被人們關注。在頻譜資源非常有限的今天&#xff0c;傳統通信系統的容量已經不能滿足當前用戶的要求。正交幅度調制QAM(Quadrature Amplitude Modulation)以其高頻…