Cómo crear su propia aplicación de chat en tiempo real

Las aplicaciones de mensajería están ganando popularidad. Los últimos años han traído aplicaciones como WhatsApp, Telegram, Signal y Line.

La gente parece preferir las aplicaciones basadas en chat porque permiten la interacción en tiempo real. También agregan un toque personal a la experiencia.

Recientemente asistí a un taller realizado por Free Software Movement Karnataka en Bangalore, donde fui mentor de un grupo de estudiantes universitarios.

Durante las interacciones, observé ciertas cosas:

  1. A pesar de animar a los estudiantes a interactuar con el mentor, la comunicación siempre fue unilateral.
  2. Los estudiantes a menudo se sentían demasiado tímidos para hacer preguntas durante las sesiones.
  3. Se sentían más cómodos haciendo preguntas y recibiendo comentarios en conversaciones individuales.

Así que teníamos que encontrar una solución para romper el hielo entre mentores y estudiantes. Una aplicación de chat local fue útil en esta situación. A las personas les encanta ser anónimas, lo que les da más poder para expresarse y preguntar en cualquier momento y lugar. Este es el mismo mantra utilizado por la mayoría de los foros populares en Internet, como Reddit y 4chan. Estos son solo algunos ejemplos gigantes de aplicaciones semi-anónimas.

Entonces comencé a pensar en esta idea. Se me ocurrieron algunos de los requisitos y características básicos.

  1. Los usuarios se registran dando un identificador, que es único para cada usuario (un nombre ficticio). Solo el identificador se revelará a otros usuarios. Por lo tanto, las personas son libres de elegir cualquier identificador y, por lo tanto, permanecen en el anonimato.
  2. Un miembro puede ver a otros miembros que están en línea. Tienen la opción de hacerlo público, lo que transmite el mensaje a todos los miembros en línea en el chat.
  3. Para los mensajes privados, el remitente debe enviar primero una solicitud al otro miembro. Otros miembros al aceptar la solicitud pueden tener un chat privado con ellos.

Tecnología, Herramientas utilizadas

  1. Pila MEAN (Mongo, Express, Angular, Node).
  2. Zócalos para permitir la comunicación uno a uno en tiempo real
  3. AJAX para registrarse e iniciar sesión

Entonces, ¿cómo se crea una aplicación de chat simple?

En este tutorial, te ayudaré a crear tu propia aplicación de chat. ¡Luego puede integrarlo como un widget en cualquier proyecto! Este tutorial no se concentrará en el desarrollo completo de una aplicación de chat. Pero te ayudará a construir uno.

Requisito previo: Necesita conocer algunos conocimientos básicos de MEAN Stack, ya que lo estamos utilizando para construir uno.

Primero, cree una estructura de directorio similar a esta.

Instale Node.js y MongoDB.

Usaremos AngularJS 1 para este tutorial. Descargue la biblioteca AngularJS desde aquí y cópiela en la carpeta lib en el directorio del Cliente.

Si desea embellecer la aplicación, puede descargar cualquier biblioteca CSS y copiarla en la biblioteca también.

Construyendo el servidor

Paso 1 - Inicie el proyecto:

Vaya al directorio del servidor y ejecute este comando:

npm init

Esto iniciará un nuevo proyecto. Proporcione todos los detalles requeridos. Se creará el package.json y se verá así.

{ "name": "chat", "version": "1.0.0", "description": "Chat application", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Your name", "license": "ISC" }

Paso 2 : instala las dependencias.

  • socket.io : es una biblioteca javascript para aplicaciones web en tiempo real. Permite la comunicación bidireccional en tiempo real entre servidores y clientes web.
  • express : es un marco de aplicación web Node.js. Proporciona el conjunto de funciones para desarrollar aplicaciones web y móviles. Uno puede responder a la solicitud HTTP utilizando diferentes middlewares y también representar páginas HTML.
npm install --save socket.io npm install --save express

Esto instalará las dependencias necesarias y las agregará a package.json. Se agregará un campo adicional a package.json que se verá así:

"dependencies": { "express": "^4.14.0", "socket.io": "^1.4.8" }

Paso 3: creación del servidor

Cree un servidor que sirva en el puerto 3000 y enviará el html cuando sea llamado.

Inicialice una nueva conexión de socket pasando el objeto HTTP.

La conexión del evento escuchará los sockets entrantes.

Cada socket emite un evento de desconexión que se llamará cada vez que un cliente se desconecte.

  • socket.on espera el evento. Siempre que se activa ese evento, se llama a la función de devolución de llamada.
  • io.emit se usa para emitir el mensaje a todos los sockets conectados a él.

La sintaxis es:

socket.on('event', function(msg){}) io.emit('event', 'message')

Cree un servidor con el nombre server.js. Debería:

  • imprimir un mensaje en la consola cuando un usuario se conecta
  • Escuche los eventos de mensajes de chat y transmita el mensaje recibido a todos los enchufes conectados.
  • Siempre que un usuario se desconecta, debe imprimir el mensaje en la consola.

El servidor se verá así:

var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendfile('index.html'); }); io.on('connection', function(socket){ console.log('user connected'); socket.on('chat message', function(msg){ io.emit('chat message', msg); }); socket.on('disconnect', function(){ console.log('user disconnected'); }); }); http.listen(3000, function(){ console.log('listening on *:3000'); });

Construyendo el cliente

Cree el index.html en el directorio del cliente, style.css en el directorio css y app.js en el directorio js del cliente.

index.html:

Escribamos un HTML simple que pueda tomar nuestro mensaje y también mostrarlo.

Include socket.io-client and angular.js in your HTML script.

socket.io serves the client for us. It defaults to connect to the host that serves the page. Final HTML looks something like this:

   Socket.IO chat         
    
    Send

    css/style.css:

    Give it some styling so that it looks like a chatbox. You can make use of any libraries.

    * { margin: 0; padding: 0; box-sizing: border-box; } body { font: 13px Helvetica, Arial; } div { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; } div input { border: 0; padding: 10px; width: 90%; margin-right: .5%; } div button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; } #messages { list-style-type: none; margin: 0; padding: 0; } #messages li { padding: 5px 10px; } #messages li:nth-child(odd) { background: #eee; }

    js/app.js:

    Create an angular.js app and initialize a socket connection.

    • socket.on listens for a particular event. It calls a callback function whenever that event is called.
    • socket.emit is used to emit the message to the particular event.

    Basic syntax of both are:

    socket.on(‘event name’, function(msg){}); socket.emit('event name', message);

    So whenever the message is typed and the button is clicked, call the function to send the message.

    Whenever the socket receives a message, display it.

    The JavaScript will look something like this:

    var app=angular.module('myApp',[]); app.controller('mainController',['$scope',function($scope){ var socket = io.connect(); $scope.send = function(){ socket.emit('chat message', $scope.message); $scope.message=""; } socket.on('chat message', function(msg){ var li=document.createElement("li"); li.appendChild(document.createTextNode(msg)); document.getElementById("messages").appendChild(li); }); }]);

    Running the application

    Go to server directory where our server is present. Run the server using the following command:

    node server.js

    The server starts running on port 3000. Go to the browser and type the following url:

    //localhost:3000

    How to improve the same application

    You can design a database to save user details and messages. It would be good if the design was scalable so that you could add more features later.

    You need to install Mongoose or a MongoDB module to make use of a Mongo database:

    npm install --save mongoose

    or:

    npm install --save mongodb

    Here’s the documentation to use mongoose and the mongodb module.

    Here’s what my schema design looks like:

    { “_id” : ObjectId(“5809171b71e640556be904ef”), “name” : “Sudheesh Shetty”, “handle” : “sudheesh”, “password” : “556624370”, “phone” : “8888888888”, “email” : “[email protected]”, “friends” : [ { “name” : “abc”, “status” : “Friend” }, { “name” : “xyz”, “status” : “Friend” } ], “__v” : 0 }

    Here, the status of each member can be:

    • Friend: Stating that the member is a friend.
    • Pending: If the member has not yet accepted.
    • Blocked: If the member has blocked the other member.

    Suppose the member has rejected a chat request. The sender can then send a chat request again. A user can also save the messages by creating an extra collection. Each document will have the message, sender, receiver, and time.

    So design your database according to your specific needs and how you want to handle messages.

    2. Create REST APIs to serve the client. For example, an endpoint that sends a home page, from which users can make other requests.

    Few of my API endpoints are:

    app.post(‘/register’,function(req,res){}) app.post(‘/login’,function(req,res){}) app.post(‘/friend_request’,function(req,res){}) app.post(‘/friend_request/confirmed’,function(req,res){})

    3. Think of some cool additional features and implement them.

    I have created a chat application of my own:

    sudheeshshetty/Chat

    Contribute to Chat development by creating an account on GitHub.github.com

    Here’s a quick glance at my chat application:

    Please do look at it, and give it a star at the top right if you like it. There are many ways I could improve this application. If you have any suggestions, send them to me at [email protected]

    You can follow me here on click the green heart if you found this helpful so that more people will see this. You can also follow me on GitHub and twitter.