使用socket io和rethinkdb构建一个聊天应用程序
A lot of tutorials can be found that teach you how to build a chat app with Socket.io. However, have you ever wondered how to best persist those chat messages?
可以找到很多教程,它们教您如何使用Socket.io构建聊天应用程序。 但是,您是否曾经想过如何好地保留这些聊天消息?
Enter RethinkDB, a realtime schema-less database. You can store and handle documents easily, just like in MongoDB, but it has reactivity built into it. That means you can subscribe to queries and get notified when data changes, making it the perfect choice when it comes to storing chat messages.
输入RethinkDB,这是一个实时的无模式数据库。 您可以像在MongoDB中一样轻松地存储和处理文档,但是它内置了React性。 这意味着您可以订阅查询并在数据更改时得到通知,这使其成为存储聊天消息的理想选择。
In this article, you will learn how to create a simple chat app with Socket.io and persist the messages in RethinkDB. To show the usefulness of a reactive database, we will also add a simple bot that reacts when you address it.
在本文中,您将学习如何使用Socket.io创建一个简单的聊天应用程序并将消息保留在RethinkDB中。 为了展示React型数据库的有用性,我们还将添加一个简单的机器人,当您处理它时会做出React。
You can also try the running app, or check out the code repository.
您也可以尝试运行的应用程序 ,或签出代码存储库 。
应用程序设置 (Application setup)
We will build a Node.js app, so you need to have node
and npm
installed. If you want to deploy your app to Heroku, you will also need a Heroku account, as well having their CLI installed. To run your app locally, you need to install and run a RethinkDB instance.
我们将构建一个Node.js应用程序,因此您需要安装node
和npm
。 如果要将应用程序部署到Heroku,则还需要一个Heroku帐户 ,并安装其CLI 。 要在本地运行您的应用,您需要安装并运行RethinkDB实例 。
To create the application, run the following in a terminal.
要创建该应用程序,请在终端中运行以下命令。
$ mkdir rethink-chat && cd rethink-chat$ npm init -y$ npm install rethinkdb express morgan http socket.io lorem-ipsum
This will initialize a Node.js app and install all required dependencies.
这将初始化Node.js应用并安装所有必需的依赖项。
准备一个Heroku应用 (Prepare a Heroku app)
In order to deploy the application to Heroku we need to create a Heroku app:
为了将应用程序部署到Heroku,我们需要创建一个Heroku应用程序:
$ git init$ heroku create
We will also need a RethinkDB instance to store and subscribe to the chat messages sent between users. You can do this via the RethinkDB Cloud add-on as follows:
我们还将需要一个RethinkDB实例来存储和订阅用户之间发送的聊天消息。 您可以通过RethinkDB Cloud插件执行以下操作:
$ heroku addons:create rethinkdb
The RethinkDB Cloud add-on is currently in alpha. Request an invite for your Heroku account email.
RethinkDB Cloud附加组件当前处于Alpha状态。 请求邀请您的Heroku帐户电子邮件 。
构建服务器 (Building the server)
To begin, let us set up the Node.js server. Create an index.js
file and add the following server skeleton. We use an Express.js server to handle http traffic and Socket.io to handle WebSocket connections with clients.
首先,让我们设置Node.js服务器。 创建一个index.js
文件,并添加以下服务器框架。 我们使用Express.js服务器处理http流量,并使用Socket.io处理与客户端的WebSocket连接。
-
相关文章