1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 使用Chatkit构建Node.js命令行聊天应用程序

使用Chatkit构建Node.js命令行聊天应用程序

时间:2022-07-28 02:47:55

相关推荐

使用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 /chatkit and clickSign Up. Within the dashboard, beneath “Chatkit”, hitCreate new +then enter a name for the instance. I called mine “My Awesome Chatkit App!”:

要创建一个,请访问/chatkit并单击“注册”。 在仪表板内的“ Chatkit”下,单击“创建新+”,然后输入实例的名称。 我称我为“我的超赞聊天工具应用!”:

Within theKeystab, take note of yourInstance LocatorandSecret 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 theInspectorto 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/authenticateroute that returns a Chatkit token.

在本教程中,我们不会对用户进行身份验证-我们不会要求他们提供密码-但我们仍然需要编写/authenticate路由来返回Chatkit令牌 。

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

此外,我们需要定义一个名为/users的路由,以创建一个Chatkit用户。

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

为此,请创建一个新文件夹,我称为mineterminal-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 calledserver.jsand paste in the following code:

然后,创建一个名为server.js的新文件,并粘贴以下代码:

Remember to replaceYOUR_INSTANCE_LOCATORandYOUR_CHATKIT_KEYwith 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/chatkitandjsdom:

在同一项目中,安装@pusher/chatkitjsdom

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

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

为了清楚起见,在上一步中,我们安装了Chatkit服务器SDK(@pusher/chatkit-server),在这里,我们安装了客户端Chatkit SDK(@pusher/chatkit-client)。 我们还安装了jsdom,但jsdom更多介绍。

In a new file calledclient.js, paste the following:

在名为client.js的新文件中,粘贴以下内容:

Starting at the top, we first importChatManagerandTokenProviderfrom@pusher/chatkit. We’ll reference these soon.

从顶部开始,我们首先从@pusher/chatkit导入ChatManagerTokenProvider。 我们将尽快参考这些内容。

We also importjsdom, the dependency I mentioned earlier.

我们还导入了前面提到的jsdom

In a nutshell,@pusher/chatkit-clientworks in the browser but not in Node. In a function calledmakeChatkitNodeCompatible, we usejsdomto “trick” Chatkit into thinking it’s running in the browser ?. This is a temporaryworkaround, but it works perfectly.

简而言之,@pusher/chatkit-client在浏览器中有效,而在Node中不起作用。 在一个名为makeChatkitNodeCompatible的函数中,我们使用jsdom来“欺骗” Chatkit,使其认为它正在浏览器中运行? 这是在应急解决方法上,但它可以完美运行。

At the bottom of the module, we define anasyncfunction calledmain, which enables us to useawaitwhen calling asynchronous functions.

在模块的底部,我们定义了一个名为mainasync函数,该函数使我们能够在调用异步函数时使用await

Ifawaitis 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 useprompt.

在允许用户加入房间之前,我们需要提示他们输入名称。 为此,我们可以使用prompt.

First, installprompt:

首先,安装prompt

npm install --save prompt

And then, import it:

然后导入:

Then, update our main function:

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

Now, if we run the app with the commandnode 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/usersroute usingaxios, which is a HTTP client:

为此,我们将使用axios将请求发送到/users路由,axios是HTTP客户端:

npm install --save axios

After installingaxios, import it:

安装axios,将其导入:

Then, define a function calledcreateUser:

然后,定义一个名为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 withnode server.jsand in the other, run the client withnode client.js. If all is well, youshouldbe prompted for a username, and you’ll seeUser created: <username> in the server output.

打开两个终端窗口。 一种是使用node server.js启动服务器,另一种是使用node client.js运行客户node client.js。 如果一切正常,则系统将提示您输入用户名,并且服务器输出User created: <username>。

If you see an error along the lines ofFailed to create a user, connect ECONNREFUSEDthen 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 tocreateUser, paste the following:

为此,在您刚刚对createUser进行的调用下面,粘贴以下内容:

Again, remember to replace yourYOUR_INSTANCE_LOCATORwith theInstance Locatoryou noted earlier.

同样,请记住将您的YOUR_INSTANCE_LOCATOR替换为您之前提到的实例定位器

This code initialises Chatkit then connects to the service, returning thecurrentUser. Note how we provide aTokenProviderwhich points toour 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 inclient.jsto fetch joinable rooms (getJoinableRooms), and list them alongside the rooms a user hasalreadyjoined (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 ,它提供了合并两个或更多数组的简洁方法。

Runningnode client.jsshould 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 thecreateRoomfunction.

您可能只会看到一个房间开始。 要创建其他房间,请返回检查器或使用createRoom功能。

订阅房间 (Subscribe to a room)

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

接下来,我们应使用以下代码提示用户选择房间:

One cool thing aboutpromptis that you can create validation rules. Above, we create one to make sure the user’s input is between0and the number of joinable rooms.

关于prompt一件很酷的事情是,您可以创建验证规则。 在上面,我们创建一个以确保用户输入的值在0到可连接房间的数量之间。

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

选择了用户的房间后,我们可以将其设置为room并订阅该房间:

Upon subscribing, we add aonNewMessagehook.

订阅后,我们添加了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.

您可以将钩子视为事件发生时调用的函数。 在这种情况下,就是收到新消息的时候。

onNewMessagewill be called inreal-timewhenever a new message is sent by “a user”. When I say “a user”, thatincludesthe 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, installreadlineto 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 applicationfeelfaster, let’s add a nifty loading spinner:

与以往一样,通过网络发送数据可能需要一到两秒钟。 对于一点乐趣,并且使我们的应用程序的感觉速度更快,让我们添加一个漂亮的加载微调:

First, installora, a loading spinner module:

首先,安装ora,它是一个加载微调器模块:

npm install --save ora

Then, inclient.js,we can callstart,succeed, etc. depending on the status of the command.

然后,在client.js,我们可以根据命令的状态调用startsucceed等。

Here’s the completeclient.jsfile, 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根据本文创建了一个视频教程。 看看这个!

翻译自: /news/build-a-node-js-command-line-chat-application-with-chatkit-8d0c4546085e/

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。