Cómo construí una aplicación de chat pública y anónima en JavaScript

Todos estamos familiarizados con la mensajería instantánea y la usamos para chatear con la gente en tiempo real. A veces, sin embargo, es posible que deseemos una aplicación que nos permita enviar mensajes de forma anónima a amigos o chatear de forma anónima con extraños en las proximidades. Un ejemplo de una aplicación de este tipo es Truth, que le permite hablar con personas de su lista de contactos sin revelar su identidad.

En este tutorial, le mostraré cómo crear una aplicación de chat público anónimo en JavaScript (usando NodeJS y Express en el servidor y VanillaJS en el cliente) y Pusher. Pusher nos permite crear aplicaciones escalables y confiables en tiempo real. Dado que necesitamos la entrega de mensajes de chat en tiempo real, este es un componente clave de la aplicación de chat. La siguiente imagen muestra lo que estaremos construyendo:

Empezando

Comencemos registrándonos para obtener una cuenta gratuita de Pusher (o iniciando sesión si ya tienes una). Una vez que haya iniciado sesión, cree una nueva aplicación Pusher desde el panel y tome nota de su ID de aplicación, Clave y Secreto, que son exclusivos de una aplicación.

Para crear una nueva aplicación Pusher, haga clic en el Your appsmenú lateral y luego en elCreate a new appbotón debajo del cajón. Esto abre el asistente de configuración.

  1. Ingrese un nombre para la aplicación. En este caso, lo llamaré "chat".
  2. Seleccione un clúster.
  3. Seleccione la opción "Crear aplicación para múltiples entornos" si desea tener diferentes instancias para el desarrollo, la puesta en escena y la producción.
  4. Seleccione Vanilla JS como frontend y NodeJS como backend.
  5. Complete el proceso haciendo clic en el Create my appbotón para configurar su instancia de aplicación.

Codifica el servidor

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.

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.

$ npm init

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

$ npm install –save pusher express body-parser

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

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.

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.

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.

@import url("//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.