我如何用JavaScript构建公开的匿名聊天应用程序

by Peter Mbanugo

彼得·姆巴努戈(Peter Mbanugo)

我如何用JavaScript构建公开的匿名聊天应用程序 (How I built a public, anonymous chat app in JavaScript)

We’re all familiar with instant messaging and using it to chat to people in realtime. Sometimes, though, we might want an app which allows us to send messages anonymously to friends, or to chat anonymously with strangers in close proximity. An example of such an app is Truth, which lets you talk with people on your contact list without disclosing your identity.

我们都熟悉即时消息传递并使用它与人们实时聊天。 但是,有时候,我们可能需要一个允许我们匿名向朋友发送消息或与附近的陌生人匿名聊天的应用。 这种应用程序的一个示例是Truth ,它使您可以与联系人列表中的人交谈,而无需透露您的身份。

In this tutorial, I’ll be showing you how to build a public anonymous chat app in JavaScript (using NodeJS and Express on the server, and VanillaJS on the client) and Pusher. Pusher allows us to build scalable and reliable realtime applications. Since we need realtime delivery of chat messages, this is a key component of the chat app. The image below depicts what we will be building:

在本教程中,我将向您展示如何使用JavaScript(在服务器上使用NodeJS和Express,在客户端上使用VanillaJS)和Pusher构建公共匿名聊天应用程序。 Pusher使我们能够构建可扩展且可靠的实时应用程序。 由于我们需要实时传递聊天消息,因此这是聊天应用程序的关键组成部分。 下图描述了我们将要构建的内容:

入门 (Getting Started)

Let’s kick off by signing up for a free Pusher account (or logging in if you already have one). Once you’re logged in, create a new Pusher app from the dashboard and make a note of your App ID, Key, and Secret, which are unique to an app.

让我们从注册一个免费的Pusher帐户开始 (或者如果已经有一个帐户 ,则登录)。 登录后,从仪表板创建一个新的Pusher应用程序,并记下应用程序唯一的应用程序ID,密钥和机密。

To create a new Pusher app, click the Your apps side menu, then click the Create a new app button below the drawer. This brings up the setup wizard.

要创建新的Pusher应用,请单击“ Your apps侧边菜单,然后单击“ Create a new app 抽屉下方的按钮。 这将显示安装向导。

  1. Enter a name for the application. In this case, I’ll call it “chat”.

    输入应用程序的名称。 在这种情况下,我将其称为“聊天”。
  2. Select a cluster.

    选择一个集群。
  3. Select the option “Create app for multiple environments” if you want to have different instances for development, staging, and production.

    如果要使用不同的实例进行开发,登台和生产,请选择“为多个环境创建应用程序”选项。
  4. Select Vanilla JS as the frontend and NodeJS as the backend.

    选择Vanilla JS作为前端,选择NodeJS作为后端。

  5. Complete the process by clicking the Create my app button to set up your app instance.

    通过单击“ Create my app按钮以设置您的应用程序实例来完成该过程。

编码服务器 (Code-up the server)

We need a backend which will serve our static files and also accept messages from a client and then broadcast to other connected clients through Pusher. Our backend will be written in NodeJS, so we need to set it up.

我们需要一个后端,该后端将提供我们的静态文件并接受来自客户端的消息,然后通过Pusher广播到其他连接的客户端。 我们的后端将用NodeJS编写,因此我们需要对其进行设置。

We need a package.json file, and I’ll add it by running the command below. I’ll use the defaults provided by hitting enter for every prompt.

我们需要一个package.json文件,我将通过运行以下命令来添加它。 我将使用在每个提示中按Enter键提供的默认值。

$ npm init

$ npm初始化

With the package.json file added, I’ll install Express, body-parser, and Pusher npm packages. Run the following command:

添加package.json文件后,我将安装Expressbody-parserPusher npm软件包。 运行以下命令:

$ npm install –save pusher express body-parser

$ npm install –保存pusher express正文解析器

With these packages installed, let’s add a new file called server.js with the following content:

安装这些软件包后,让我们添加一个名为server.js的新文件,其内容如下:

var express = require('express');var bodyParser = require('body-parser');var Pusher = require('pusher');
var app = express();app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false }));
var pusher = new Pusher({ appId: "APP_ID", key: "APP_KEY", secret:  "APP_SECRET", cluster: "APP_CLUSTER" });
app.post('/message', function(req, res) {  var message = req.body.message;  pusher.trigger( 'public-chat', 'message-added', { message });  res.sendStatus(200);});
app.get('/',function(req,res){           res.sendFile('/public/index.html', {root: __dirname });});
app.use(express.static(__dirname + '/public'));
var port = process.env.PORT || 5000;app.listen(port, function () {  console.log(`app listening on port ${port}!`)});

With the code above, we have defined an end-point /message which will be used by one client to send a message to another through Pusher. The other routes are used to serve the static files which we will add later.

通过上面的代码,我们定义了一个端点/message ,一个客户端将使用该端点/message通过Pusher向另一个客户端发送消息。 其他路由用于提供静态文件,我们将在以后添加。

Replace the placeholder strings App ID, Secret, and Key with the values from your Pusher dashboard. Add this statement "start": "node server.js" in the script property of our package.json file. This will allow us to start the server when we run npm start.

将占位符字符串App ID,Secret和Key替换为Pusher仪表板中的值。 在package.json文件的script属性中添加以下语句"start": "node server.js" 。 这将允许我们在运行npm start时启动服务器。

建立前端 (Building the frontend)

Moving on to the frontend, let’s add a new folder called public. This folder will contain our page and JavaScript files. Add a new file called style.css with the content below, which will hold our style definition for the page.

转到前端,让我们添加一个名为public的新文件夹。 该文件夹将包含我们的页面和JavaScript文件。 添加一个名为style.css的新文件,其内容如下,该文件将保留页面的样式定义。

@import url("http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css");.chat{    list-style: none;    margin: 0;    padding: 0;}
.chat li{    margin-bottom: 10px;    padding-bottom: 5px;    border-bottom: 1px dotted #B3A9A9;}
.chat li.left .chat-body{    margin-left: 60px;}
.chat li.right .chat-body{    margin-right: 60px;}
.chat li .chat-body p{    margin: 0;    color: #777777;}
.panel .slidedown .glyphicon, .chat .glyphicon{    margin-right: 5px;}
.body-panel{    overflow-y: scroll;    height: 250px;}
::-webkit-scrollbar-track{    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);    background-color: #F5F5F5;}
::-webkit-scrollbar{    width: 12px;    background-color: #F5F5F5;}
::-webkit-scrollbar-thumb{    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);    background-color: #555;}

Add another file called index.html with the markup below.

使用下面的标记添加另一个名为index.html的文件。

<!DOCTYPE html><html><head>    <!-- Latest compiled and minified CSS -->    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script        src="https://code.jquery.com/jquery-2.2.4.min.js"        integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="        crossorigin="anonymous"><;/script>
<!-- Latest compiled and minified JavaScript -->    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"&gt;</script>
<link rel="stylesheet" href="style.css">    <script src="https://js.pusher.com/4.0/pusher.min.js"></script>    <script src="index.js"></script></head><body>    <div class="container">    <div class="row form-group">        <div class="col-xs-12 col-md-offset-2 col-md-8 col-lg-8 col-lg-offset-2">            <div class="panel panel-primary">                <div class="panel-heading">                    <span class="glyphicon glyphicon-comment"></span> Anonymous Chat                    <div class="btn-group pull-right">                        <button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">                            <span class="glyphicon glyphicon-chevron-down"></span>                        </button>                        <ul class="dropdown-menu slidedown">                            <li><a href="http://www.jquery2dotnet.com"><span class="glyphicon glyphicon-refresh">                            </span>Refresh</a></li>                            <li><a href="http://www.jquery2dotnet.com"><span class="glyphicon glyphicon-ok-sign">                            </span>Available</a></li>                            <li><a href="http://www.jquery2dotnet.com"><span class="glyphicon glyphicon-remove">                            </span>Busy</a></li>                            <li><a href="http://www.jquery2dotnet.com"><span class="glyphicon glyphicon-time"></span>                                Away</a></li>                            <li class="divider"></li>                            <li><a href="http://www.jquery2dotnet.com"><span class="glyphicon glyphicon-off"></span>                                Sign Out</a></li>                        </ul>                    </div>                </div>                <div class="panel-body body-panel">                    <ul class="chat">
</ul>                </div>                <div class="panel-footer clearfix">                    <textarea id="message" class="form-control" rows="3"></textarea>                    <span class="col-lg-6 col-lg-offset-3 col-md-6 col-md-offset-3 col-xs-12" style="margin-top: 10px">                        <button class="btn btn-warning btn-lg btn-block" id="btn-chat">Send</button>                    </span>                </div>            </div>        </div>    </div></div>
<script id="new-message-other" type="text/template">    <li class="left clearfix">        <span class="chat-img pull-left">            <img src="http://placehold.it/50/55C1E7/fff&text=U" alt="User Avatar" class="img-circle" />        </span>        <div class="chat-body clearfix">            <p>                {{body}}            </p>        </div>    </li></script>
<script id="new-message" type="text/template">    <li id="{{id}}" class="right clearfix">        <div class="chat-body clearfix">            <p>                {{body}}            </p>        </div>    </li></script>
</body>&lt;/html>

I’m using a template from bootsnipp which has been slightly modified to display just the name and message.

我正在使用bootsnipp中的模板,该模板已经过稍微修改以仅显示名称和消息。

Add a new file called index.js with the content below. Remember to add the Pusher app details:

在下面的内容中添加一个名为index.js的新文件。 记住要添加Pusher应用程序详细信息:

$(document).ready(function(){        var pusher = new Pusher('APP_KEY', {        cluster: 'APP_CLUSTER',        encrypted: false    });
let channel = pusher.subscribe('public-chat');    channel.bind('message-added', onMessageAdded);
$('#btn-chat').click(function(){        const message = $("#message").val();        $("#message").val("");
//send message        $.post( "http://localhost:5000/message", { message } );    });
function onMessageAdded(data) {        let template = $("#new-message").html();        template = template.replace("{{body}}", data.message);
$(".chat").append(template);    }});

With the code in this file, we get the message to be sent and then call the server with the message. After that, we connect to Pusher by creating a new Pusher object with the App Key and the Cluster that you set earlier.

使用此文件中的代码,我们得到要发送的消息,然后使用该消息调用服务器。 之后,我们通过使用您先前设置的App Key和Cluster创建一个新的Pusher对象,从而连接到Pusher。

We subscribe to a channel and an event named message-added. The channel is a public channel so it can be named any way you like. I’ve chosen to prefix mine with public- but that’s just my own personal naming convention as there are no rules for a public channel. The difference between a public channel and a private or presence channel is that a public channel does not require a client to be authenticated and can be subscribed to by anyone that knows the name of the channel. You can read more about Pusher channels here.

我们订阅了一个频道和一个名为message-added的事件。 该频道是公共频道,因此您可以随意命名。 我选择在我的名字前面加上public-但这只是我个人的命名约定,因为没有公开频道的规则。 public频道与privatepresence频道之间的区别在于,公用频道不需要对客户端进行身份验证,并且知道该频道名称的任何人都可以订阅该频道。 您可以在此处阅读有关Pusher频道的更多信息。

We bind to the click event of the chat button on the page, retrieve the message from the textbox on the page, and then send it to the server with the username. With all we have setup, we can start the app by running npm start. Here’s a glimpse of how it works on my computer.

我们绑定到页面上聊天按钮的click事件,从页面上的文本框中检索消息,然后使用用户名将其发送到服务器。 完成所有设置后,我们可以通过运行npm start来启动应用npm start 。 这是我的计算机上工作方式的一瞥。

结语 (Wrap Up)

This is a app to show how you can use Pusher to send messages in real-time. We built a public anonymous chat app that allows your website visitors to send anonymous messages to each other in real-time. You can find the code here on GitHub

这是一个应用程序,展示了如何使用Pusher实时发送消息。 我们构建了一个公共匿名聊天应用程序,使您的网站访问者可以实时向彼此发送匿名消息。 您可以在GitHub上找到代码

This was originally published on Pusher

这最初发布在Pusher上

翻译自: https://www.freecodecamp.org/news/how-i-built-a-public-anonymous-chat-app-in-javascript-34f082b9b98/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值