1678540620
This repository contains server & client side code using TypeScript
language
Running Server and Client locally
First, ensure you have the following installed:
After that, use Git bash
to run all commands if you are on Windows platform.
In order to start the project use:
$ git clone https://github.com/luixaviles/socket-io-typescript-chat.git
$ cd socket-io-typescript-chat
To run server locally, just install dependencies and run gulp
task to create a build:
$ cd server
$ npm install -g gulp-cli
$ npm install
$ gulp build
$ npm start
The socket.io
server will be running on port 8080
When you run npm start
, this folder leverages nodemon which will automatically reload the server after you make a change and save your Typescript file. Along with nodemon, there is also a gulp watch
task that you can run to reload the files but it's not necessary and is provided merely as a teaching alternative.
Open other command line window and run following commands:
$ cd client
$ npm install
$ ng serve
Now open your browser in following URL: http://localhost:4200
Server Deployment
Take a look the Wiki Page for more details about deploying on Heroku
and Zeit.co
.
Feel free to update that page and Readme if you add any other platform for deployment!
Forks
The Open Source community is awesome! If you're working in a fork with other tech stack, please add the reference of your project here:
Features | Author | Status |
---|---|---|
React + TypeScript + Material-UI client | nilshartmann | In Progress |
Read the blog post with details about this project: Real Time Apps with TypeScript: Integrating Web Sockets, Node & Angular
Try live demo: https://typescript-chat.firebaseapp.com
Support this project
Author: luixaviles
Source Code: https://github.com/luixaviles/socket-io-typescript-chat
License: MIT license
1678243336
在本教程中,我们将学习如何使用 Socket.io 创建对话 | 反应聊天应用程序
我们希望您觉得这篇文章真的很有帮助。不仅因为我们必须讨论React游戏应用程序的理论方面,它们的重要性和用途,还因为我们将讨论构建 React 游戏应用程序。利用Flatlogic 的Full Stack Web App Builder来应对这一现实。- 新的应用程序。一个伟大的工具,旨在减少从头开始构建应用程序的疲劳。
让我们从传统问题开始:“什么是 React 聊天应用程序?”。这个问题的答案很简单:React 聊天应用程序是一个应用程序,其主要目的是为客户和/或客户提供与项目代表沟通的能力,以帮助他们解决他们可能遇到的任何问题项目。. 此外,聊天应用程序允许您以其他方式与客户沟通,例如向他们提供项目新闻、更新以及您提供的任何其他信息。游戏应用程序的另一个非常重要的功能是能够以数字形式存储客户数据,例如姓名、地址、消息等。
目前这类应用需求量大,市场上有大量的业务和项目,客户-企业模式(或广义的需求-供应模式)更趋向于客户导向。这意味着对于现代公司而言,与客户建立和谐关系比反之更重要,因为如果客户对他们的服务不满意,他们的愿望和需求可以通过公司更容易地被竞争对手满足,反之亦然。现公司。因此,在您和客户之间保持牢固的关系变得越来越重要,包括提供一对一的支持。没有竞争对手和替代品的独特业务和项目短期内可能不会出现这个问题,但我们必须强调,问题不仅仅存在于短期内。原因很简单,即使用竞争对手和替代品发现的独特产品总是迟早的事。这就是为什么保持良好的关系很重要。幸运的是,借助聊天应用程序可以轻松实现这一目标。curto prazo, embora devamos frisar que o problema not é so de curto prazo. Razão para isso é o simples fato de que semper uma questão de tempo até que um produto único adquira esmperentes 和替代品。É por isso que manter bons relacionamentos é essencial。幸运的是,借助聊天应用程序可以轻松实现这一目标。
所以,在那之前,你的项目需要的大部分聊天应用都是未来的,你的语音分配人的解释是 React。E a resposta curta seria que os aplicativos de bate-papo baseados no React。JS要快,escaláveis 和 fáceis de manter para desenvolvedores。不用担心,存在于接受数据棉塞、mas sugerimos、mesmo assim、或使用 ReactJS 的编程语言之外,pois 没有必要使用 em caminho mais longo 和 ventoso。这是一个问题,您将无法继续简化甚至无法将Full Stack Web App Builder 与 Flatlogic 一起使用。这将我们带到下一个主题。
在本文的这一部分,我们将讨论两种构建 React Chat 应用程序的方法:
来测试第一种方法。在这种情况下,有必要执行两个主要步骤,每个步骤都有许多子步骤:
使用此方法编写 React bate-papo 应用程序后,您的 bate-papo 应用程序中的所有信息和数据将受到 E2E 加密保护。Mas vamos ser mais específicos e olhar mais de perto。
方法一、Criando和内部加密
对于革命的第一部分,这是一个内部想法,我们使用了 Express 和 Node.js 构建工具。它用作内部和外部服务的真正双向 fornecer 通信对象。
此模式的第二部分是内部加密,分为发送服务目录和导航器初步创建的子补丁。O havedigo ficaria da seguinte forma:
聊天服务器端 mkdir
辅助聊天CD
您还需要编写package.json 。Para fazer isso, insira o seguinte trecho de Código without terminal:
npm init –y
因此,例如,这是pack.json。
要改变这种情况,请这样做:
点击 dummyuser.js。
将 dummyuser.js 添加到存档中:
const cusers = [];
function joinUser(id, username, room) {
const puser = { id, username, room };
cusers.push(puser);
console.log(cusers, "users");
return p_user;
}
console.log("user out", cusers);
function getCurrentUser(id) {
return cusers.find((puser) => puser.id === id);
}
const index = cusers.findIndex((puser) => puser.id === id);
if (index !== -1) {
return cusers.splice(index, 1)[0];
}
module.exports = {
joinUser,
getCurrentUser,
userDisconnect,
};
touch server.js
添加或 server.js 文件:
const express = require("express");
const app = express();
const socket = require("socket.io");
const color = require("colors");
const cors = require("cors");
const { getCurrentUser, userDisconnect, joinUser } = require("./dummyuser");
app.use(express());
const port = 8000;
app.use(cors());
var server = app.listen(
port,
console.log(`Server is running on the port no: ${port} `.green)
);
const io = socket(server);
io.on("connection", (socket) => {
socket.on("joinRoom", ({ username, roomname }) => {
const puser = joinUser(socket.id, username, roomname);
console.log(socket.id, "=id");
socket.join(puser.room);
socket.emit("message", {
userId: puser.id,
username: puser.username,
text: `Welcome ${puser.username}`,
});
socket.broadcast.to(puser.room).emit("message", {
userId: puser.id,
username: puser.username,
text: `${puser.username} has joined the chat`,
});
});
socket.on("chat", (text) => {
const puser = getCurrentUser(socket.id);
io.to(puser.room).emit("message", {
userId: puser.id,
username: puser.username,
text: text,
});
});
socket.on("disconnect", () => {
const puser = userDisconnect(socket.id);
if (puser) {
io.to(puser.room).emit("message", {
userId: puser.id,
username: puser.username,
text: `${puser.username} has left the room`,
});
}
});
});
Agora,对于第 2 个子步骤,创建了一个依赖项并要求对用户指定 sala vazia criando 的需求进行编码作为所使用的方法矩阵。Ele tambem esvazia a matriz quando o usuário ce desconecta。
要创建依赖项,请执行以下步骤:
npm i socket.io 表达颜色 Cors
npm i -D 点头
Criar node_modules
集市,chegamos 一个 subpasso numberer。如果主要注册目标是后台存档,则用于与后台通信,提供sala de usuários的联系方式。Para concluir esta subetapa, faça o seguinte:
现在您需要预先确定会发生什么:
joinRoom 这是允许新用户加入聊天所必需的,因为它会在用户加入后提供通知,以及有关已加入聊天的用户的通知。
· 聊天
Este é 非常重要,可以让一个真正的羡慕过程和获得 mensagens。他也嫉妒那个信息能让人议论纷纷的人。
这是聊天客户端后端正在进行的工作的最终构建。
第 2 步。创建和编码用户界面。
在这一步中,我们将使用 React、Redux 库、socket.io-client,此外,还有一个名为 aes256 的工具可以帮助加密以及解密对话中包含的信息和数据的重要性。
在这种情况下,我们的第一个附加步骤是创建一个漂亮而简单的用户界面。前端流程的最后一步将如下所示:
· chartfrontend
> node_modules
> public
· src
§ chat
§ chat.js
§ chat.scss
· home
§ home.js
§ home.scss
· process
§ process.js
§ process.scss
· store
· action
§ index.js
· reducer
§ index.js
§ process.js
o _global.scss
o aes.js
o app.js
o app.scss
o index.js
{} package-lock.json
{} package.json
然后什么都不会通过 UI 编码。这部分过程由几个步骤组成,由于编码过程的第一部分比第二部分更有创意,我们将只按一般顺序描述子步骤,而不提供有关编码步骤的具体信息。
另外,No React app的client paste是一个序列号,可以作为运行app需要的依赖安装。
第二个子丝锥系列:
§ 编辑/src/index.js文件,使其更容易在您的 React 应用程序中实施缩减程序。
§ depois diso, a criação de um arquivo /store/action/index.js,需要它来识别今天没有权限离开该对象的对象,以便它可以被正确删除;
§ 接下来你需要做的是创建/store/reducer/process.js,它在应用程序中充当一个 reducer,即它将获取新操作的当前状态并将它们回滚到新状态;
§ 在下一节中,修复创建存档/store/reducer/index.js以导入引入的 reducer 并防止对象预评估;
§ e 最后 adicione redux 创建了 React 应用程序并创建了.
所有这些都是提供或羡慕并获得 mensagen 所必需的,并且羡慕我做aes.js记者写作和描述 mensagen。
完成上述所有子步骤后,我们来到numberero tres子步骤,它负责为用户名和房间生成路由查找。然后将 no 选项添加到App.js。
该小节包括为/home/home.js 存储库编写代码,该存储库用作应用程序的主页,用于使用名称以外的方法,并以接近输入的方式使用。绝对有必要写função socket.emit("joinRoom"),这样定义的没有后端的joinRoom函数后面可以有一定的机会被包含进来,一定能得到boas-vindas。报道。首先是mensionamos。Disco Depois,adicione estilos de sua escolha ao arquivo home.js。
一个小节来了,它会是一年,加密或托管在/chat/chat.js,这是一个大帐户,在sala中使用。从本质上讲,这是聊天的主页面,您可以使用它在聊天窗口中与其他用户聊天。Disco Depois、Adicione estilos de sua escolha 和 arquivo chat.js。
第二步和第六步是创建aes.js aes.js,也就是我们的加密/解密消息。
分发完成后,进入第七步,创建文件/process/process.js,负责显示秘钥,以及聊天右侧的加解密消息房间。. 之后,您将被带到您的档案。
对于电影,在最终应用之前启动服务器和你想尝试的应用。
E é assim que cria applicativo de bate-papo React,que tambem é habilitado pela cryptografia E2E。此嵌入将是一个快速而简单的过程,有效地存在以轻松打破任何使用 Web App Builder 的人。这意味着你可以使用一个有用的软件,但你可以在一个不同的软件包中使用 Flatlogic 的所有组合知识和经验。这让您知道该应用程序功能齐全且易于使用:
正因为如此,Então você pressa o botão “ Gerar applicativo ”是关于一位魔法导师的。所以我最近提出了一个不太直接的构建 React Chat 应用程序的过程,建议用户选择一个小应用程序,这样你就可以创建一个项目,使用 Full Stack Web App Builder 创建一个即时.
Toda grande history começa com um titleulo 和 todo grande applicativo React começa com um nome。最初,开发节奏很快,旨在用于 React Chat Apps,这是该项目的名称。
在此期间,您将需要一个可以应用于您的世界的元数据工具,包括任务 UI、后端和数据存储。
基本上,您已经创建了一个超模蒙太奇,所以它会立即变成您最好的照片之一,在一系列自定义选项之前创建一个令人惊叹的设计。.
在这一步中,与前面的步骤一样,为骨骼添加一些重要的肌肉。我们的意思是为您的 React Chat 应用程序创建一个数据库模式。如果你不想自己做,Flatlogic 平台有一个现成的聊天应用程序架构。现在从列表中选择所需的数据库。同样出色的是能够修改预制图表以更好地满足您的需求。
在此之前您需要做的是在使用 Full-Stack Web 应用程序时轻松地用英语测试应用程序并使用“Criar projeto”机器人 一段时间后,您将能够将代码用作完整的-精选 React bate-papo 应用程序。
在本文的这一部分,我们想与您分享我们认为非常好的前 5 个 React 聊天应用程序并解释原因。
示例 1: Joshua P. Larson 在 React 中创建的简单聊天窗口
将这个 React Chat 应用程序视为现实,让大多数人有多个人和多次重复的问题被认为是推动者并在项目中验证它们。Lento e Constante ou,mais apropriadamente for a ocasião em questão, agradável e simples, vene a Corrida。
字体 — codepots.com/library/item/3749
示例 2 ——DanLowo bate-papo 的附件
这是一个假的 React 应用程序和 cheio de estilo,我们可以将其用作男性制作 Instagram mais bem feitas 的指南。它包括当拆卸可视聊天应用程序的重要性是为了最终使用时的传输形式的示例列表。同时,我假设Full Stack Web App Builder for Flatlogic允许您开发要包含在参与选项列表中的应用程序。
字体 - github.com/DanLowo/Chat-Application
示例 3:使用chatengine.io Rest API的基于 React 的应用程序
React 聊天应用程序是由团队创建并通过 Google 授权的递归列表。这个特殊的应用程序将服务于 bastante 的贵族主题 - dar às pessoas uma plataforma para partilhar suas preoccupações 和 pensamentos com pessoa disposta a ovir de forma anônima。Portanto,par um objetivo puro e recursos matadores em nossa lista de examplesos,补丁!
字体 - reactjsexample.com/a-react-based-chat-app-using-chatengine-io-rest-api-and-has-features-of-creating-groups/
示例 4 – EfeChat de Alper Efe Şahin
我们觉得有必要将此示例添加到我们的简单翻译列表中。本质上是一种简化 React Chat 应用程序最终使用的方法。而 EfeChat 轻松解决了这个问题,因为它的功能非常简单直观——用户可能不会注意到的功能。但请相信我,如果缺少这两个功能,用户会更加注意。
字体-github.com/alper-efe-sahin/EfeChat-Reactjs
示例 5 - Asif Azad 的 bate-papo fofo
我们想用一个可爱的聊天来结束我们的列表——一个简单但时尚的聊天本身让我们回到 2000 年代的对话,比如 ICQ 的通用设计。但这不是将其包含在此列表中的重点。这对于让你的 React Chat 应用程序像可爱的聊天一样对智能手机友好是必要的,因为现在大多数互联网流量来自智能手机,而不是电脑。
资料来源:bestoreactjs.com/repo/BRAINIAC2677-cute-chat-react-react-apps。
现在让我们回顾一些要点:
这就是今天的全部内容。我们希望您觉得这篇文章真的很有帮助。祝你有美好的一天,并一如既往地阅读更多我们的文章。
文章摘自:https: //flatlogic.com
#socket #react-native #react
1678178544
В этом уроке мы узнаем, как создать беседу с помощью Socket.io | Реагировать на чат-приложение
Мы надеемся, что вы нашли эту статью действительно полезной. И не только потому, что мы должны говорить о теоретической стороне игровых приложений React , их важности и использовании, но и потому, что мы будем обсуждать создание игровых приложений React.Используйте эту реальность с помощью Full Stack Web App Builder от Flatlogic. - новое приложение. отличный инструмент, предназначенный для уменьшения усталости от создания приложений с нуля.
Начнем с традиционного вопроса: «Что такое чат-приложение React?». И ответ на этот вопрос довольно прост: чат-приложение React — это приложение, основная цель которого — предоставить клиенту и/или клиенту возможность общаться с представителями проекта, чтобы помочь им решить любые проблемы, которые могут возникнуть у них с проектом. . Кроме того, чат-приложения позволяют вам общаться с вашими клиентами другими способами, например сообщать им новости проекта, обновления и любую другую информацию, которую вы сообщаете. Еще одной очень важной особенностью игрового приложения является возможность хранения в цифровом виде данных о клиентах, таких как имена, адреса, сообщения и т. д.
В настоящее время такие приложения пользуются большим спросом, на рынке доступно большое количество бизнесов и проектов, модель клиент-предприятие (или модель спроса-предложения в широком смысле) тяготеет к большей клиентоориентированности. Это означает, что для современной компании важнее создать гармоничные отношения с клиентами, чем наоборот, потому что их желания и потребности могут быть удовлетворены конкурентами путем компании проще, чем наоборот, если клиент не удовлетворен их обслуживанием. текущая компания. Таким образом, становится все более и более важным поддерживать прочные отношения между вами и вашими клиентами, включая предоставление индивидуальной поддержки. Уникальные бизнесы и проекты, не имеющие конкурентов и альтернативможет не иметь этой проблемы в краткосрочной перспективе, хотя мы должны подчеркнуть, что проблема не только в краткосрочной перспективе. Причина этого в том простом факте, что использование уникального продукта, найденного конкурентами и заменителями, всегда является вопросом времени. Вот почему важно поддерживать хорошие отношения. К счастью, этой цели можно легко достичь с помощью чат-приложений. curto prazo, embora devamos frisar que o problema not é so de curto prazo. Razão para isso é o simples fato de que semper uma questão de tempo até que um produto único adquira esmperentes и альтернативы. É por isso que manter bons relacionamentos é essencial. К счастью, этой цели можно легко достичь с помощью чат-приложений.
Итак, до этого большинство чат-приложений, необходимых для ваших проектов, находятся в будущем, и объяснением вашего голосового назначенного человека является React. E a resposta curta seria que os aplicativos de bate-papo baseados no React. JS , чтобы он был быстрым, escaláveis и fáceis de manter para desenvolvedores. Не нужно беспокоиться, существует вне языка программирования, который принимает тампон данных, mas sugerimos, mesmo assim, o uso de ReactJS, pois не имеет necessidade de escolher um caminho mais longo и ventoso. Это такая проблема, что вы не сможете перейти к упрощению и даже сможете использовать Full Stack Web App Builder с помощью Flatlogic . И это подводит нас к следующей теме.
В этой части статьи мы обсудим два способа создания приложений React Chat:
Приходите протестировать первый способ. В этом случае необходимо выполнить два основных шага, каждый из которых имеет ряд подэтапов:
После написания приложения React bate-papo с использованием этого метода вы будете защищены всей информацией и данными в вашем приложении bate-papo с шифрованием E2E. Mas vamos ser mais específicos e olhar mais de perto.
Способ 1. Criando и внутреннее шифрование
Для первой части революции, которая была внутренней идеей, мы использовали инструменты для создания Express и Node.js. Он используется в качестве истинного двунаправленного коммуникационного объекта fornecer для внутренних и внешних служб.
Вторая часть этого режима, представляющая собой внутреннее шифрование, разбита на подпатчи, отправляющие предварительное создание сервисного каталога и вашего навигатора. O havedigo ficaria da seguinte forma:
серверная часть чата mkdir
вспомогательный чат компакт-диск
Также необходимо написать package.json . Para fazer isso, insira o seguinte trecho de Código без терминала:
npm init –y
Так, например, это pack.json .
Чтобы изменить ситуацию, сделайте это так:
коснитесь dummyuser.js.
Добавьте в архив dummyuser.js:
const cusers = [];
function joinUser(id, username, room) {
const puser = { id, username, room };
cusers.push(puser);
console.log(cusers, "users");
return p_user;
}
console.log("user out", cusers);
function getCurrentUser(id) {
return cusers.find((puser) => puser.id === id);
}
const index = cusers.findIndex((puser) => puser.id === id);
if (index !== -1) {
return cusers.splice(index, 1)[0];
}
module.exports = {
joinUser,
getCurrentUser,
userDisconnect,
};
touch server.js
Добавить или файл server.js:
const express = require("express");
const app = express();
const socket = require("socket.io");
const color = require("colors");
const cors = require("cors");
const { getCurrentUser, userDisconnect, joinUser } = require("./dummyuser");
app.use(express());
const port = 8000;
app.use(cors());
var server = app.listen(
port,
console.log(`Server is running on the port no: ${port} `.green)
);
const io = socket(server);
io.on("connection", (socket) => {
socket.on("joinRoom", ({ username, roomname }) => {
const puser = joinUser(socket.id, username, roomname);
console.log(socket.id, "=id");
socket.join(puser.room);
socket.emit("message", {
userId: puser.id,
username: puser.username,
text: `Welcome ${puser.username}`,
});
socket.broadcast.to(puser.room).emit("message", {
userId: puser.id,
username: puser.username,
text: `${puser.username} has joined the chat`,
});
});
socket.on("chat", (text) => {
const puser = getCurrentUser(socket.id);
io.to(puser.room).emit("message", {
userId: puser.id,
username: puser.username,
text: text,
});
});
socket.on("disconnect", () => {
const puser = userDisconnect(socket.id);
if (puser) {
io.to(puser.room).emit("message", {
userId: puser.id,
username: puser.username,
text: `${puser.username} has left the room`,
});
}
});
});
Agora, для подэтапы номер 2, что была создана зависимость и требовалось кодирование необходимости для пользователя указать sala vazia criando в качестве матрицы используемых средств. Ele tambem esvazia a matriz quando о usuário се desconecta.
Чтобы создать зависимость, выполните следующие действия:
npm i socket.io экспресс-цвета Cors
npm i -D nod
Criar node_modules
Agora, chegamos a subpasso numberer. Если основной зарегистрированной целью является серверный архив, он используется для установления связи с серверной частью и предоставления контактной информации для sala de usuários. Para concluir esta subetapa, faça o seguinte:
Теперь вам нужно заранее определить, что произойдет:
joinRoom Это необходимо, чтобы позволить новым пользователям присоединяться к чату, так как он предоставляет уведомления после присоединения пользователя, а также уведомления о пользователях, присоединившихся к чату .
· чат
Эсте é очень важен, может сделать реальный процесс зависти и получать mensagens. Он также завидует человеку, чья информация позволяет людям говорить о ситуации.
Это финальная сборка незавершенной работы над серверной частью клиента чата.
Шаг 2. Создание и кодирование пользовательского интерфейса.
На этом этапе мы будем использовать React, библиотеку Redux , socket.io-client, кроме того, есть инструмент под названием aes256, который помогает в шифровании и почему это важно, расшифровка информации и данных, содержащихся в разговоре.
Наш первый дополнительный шаг в этом случае — создать пользовательский интерфейс, который хорош и прост. Последний шаг процесса Front-end будет выглядеть так:
· chartfrontend
> node_modules
> public
· src
§ chat
§ chat.js
§ chat.scss
· home
§ home.js
§ home.scss
· process
§ process.js
§ process.scss
· store
· action
§ index.js
· reducer
§ index.js
§ process.js
o _global.scss
o aes.js
o app.js
o app.scss
o index.js
{} package-lock.json
{} package.json
Ничто тогда не проходит через кодирование пользовательского интерфейса. Эта часть процесса состоит из нескольких шагов, и, поскольку первая часть процесса кодирования более творческая, чем вторая, мы будем описывать только подэтапы в общем порядке, не предоставляя конкретной информации о действиях по написанию кода.
Кроме того, в качестве клиентской пасты для приложения No React выбирается подпорядковый номер серии , который можно установить в качестве зависимостей, необходимых для выполнения приложения.
Вторая серия субетапа :
§ внесите изменения в файл /src/index.js , чтобы упростить реализацию редьюсеров в вашем приложении для реагирования;
§ depois diso, a criação de um arquivo /store/action/index.js , которое необходимо для идентификации объектов, у которых нет разрешения на выход из объекта сегодня, чтобы его можно было правильно удалить;
§ следующее, что вам нужно сделать, это создать /store/reducer/process.js , который действует как редьюсер в приложении, то есть он будет принимать текущее состояние новых действий и откатывать их обратно к состоянию new;
§ В следующем разделе внесите исправление для создания архива /store/reducer/index.js для импорта введенных редюсеров и предотвращения предварительной оценки объектов;
§ e, наконец, adicione redux создал приложение React и создал процесс .
Все это необходимо для обеспечения или зависти и получения мензагена, полученного и завидующего мне, выполняющему aes.js e, репортеру, написанию и описанию менсагена.
После выполнения всех вышеупомянутых подэтапов мы подходим к подэтапу numberero tres , который отвечает за генерацию поиска маршрутов для юзернеймов и комнат. Затем добавьте параметр no для App.js .
Подчетверть состоит из написания кода для репозитория /home/home.js , который функционирует как начальная страница приложения, для методов использования , отличных от их имен, и использования в стиле, близком к enter. Абсолютно необходимо закодировать função socket.emit("joinRoom") , чтобы функция joinRoom , определенная без серверной части, могла позже использовать определенный шанс быть включенной и обязательно получить boas-vindas. отчеты. менсионамос в первую очередь. Дискотека Depois, adicione estilos de sua escolha ao arquivo home.js.
Приближается подраздел, это будет год , зашифрованный или размещенный /chat/chat.js, это большой аккаунт и используется в сала. По сути, это главная страница чата, об использовании которой можно пообщаться с другими пользователями в окне чата. Дискотека Depois, Adicione estilos де sua escolha и arquivo chat.js.
Второй и шестой шаг — создать aes.js aes.js , который является нашим сообщением о шифровании/дешифровании.
После раздачи переходим к седьмому подэтапу , который заключается в создании файла /process/process.js , отвечающего за отображение секретного ключа, а также зашифрованных и расшифрованных сообщений в правой части комнаты чата. . После этого вы попадете в свой архив.
Для фильма запустите сервер и приложение, которое вы хотите попробовать, перед финальным приложением.
E é assim que cria aplicativo de bate-papo React, que tambem é habilitado pela cryptografia E2E. Эта эмбора будет быстрым и простым процессом, который эффективно существует, чтобы легко разрушить любого с помощью Web App Builder. Это означает, что вы можете использовать одну часть полезного программного обеспечения, но вы можете использовать все остальные объединенные знания и опыт Flatlogic в одном отличающемся программном пакете. Это позволяет вам узнать, что приложение является полностью функциональным и простым в использовании:
Из-за этого Então você pressa o botão « Gerar aplicativo » рассказывает об инструкторе по магии. Поэтому недавно я предложил менее простой процесс создания приложения React Chat, порекомендовав пользователям выбрать небольшое приложение, чтобы вы могли создать проект, использующий Full Stack Web App Builder для создания мгновенного .
Toda grande history começa com um titleulo and todo grande aplicativo React começa com um nome. Изначально разработка шла стремительно и предполагалось для React Chat Apps, что и было названо названием проекта.
В течение этого времени вам понадобится инструмент метаданных, который вы сможете применить к своему миру, включая пользовательский интерфейс задачи, серверную часть и банк данных.
По сути, вы создали монтаж супермодели, поэтому он мгновенно включается в один из ваших лучших снимков, создавая потрясающий дизайн перед серией пользовательских вариантов. .
На этом шаге, как и в предыдущих шагах, добавьте несколько серьезных мышц к скелету. И мы имеем в виду создание схемы базы данных для вашего приложения React Chat. А если вы не хотите делать это самостоятельно, на платформе Flatlogic есть готовая схема для приложений чата. Теперь выберите нужную базу данных из списка. Что также здорово, так это возможность возиться с готовыми диаграммами, чтобы они лучше соответствовали вашим потребностям.
Что вам нужно сделать до этого, так это упростить проверку приложения на английском языке и применить бота «Criar projeto», пока использовать Full-Stack Web App Через некоторое время вы сможете использовать код как полнофункциональное приложение React bate-papo.
В этой части статьи мы хотим поделиться с вами 5 лучшими чат-приложениями React, которые мы считаем действительно хорошими, и объяснить, почему.
Пример 1. Простое окно чата, созданное в React Джошуа П. Ларсоном
Считайте это приложение React Chat реальностью, позволяющей большинству людей иметь несколько человек и много повторений вопросов, чтобы считаться промоутером и подтверждать их в проекте. Lento e Constante ou, mais apropriadamente for a ocasião em questão, agradável e simples, vene a Corrida.
Шрифт — codepots.com/library/item/3749
Пример 2 — приложение DanLowo bate-papo
Это поддельное приложение React и cheio de estilo, которое мы можем использовать в качестве руководства для мужчин, чтобы сделать Instagram mais bem feitas. Он включает в себя список примеров формы передачи, когда важность демонтажа приложения визуального чата предназначена для конечного использования. В то же время я предположил, что Full Stack Web App Builder для Flatlogic позволяет вам разработать приложение, которое вы хотите включить в список участвующих вариантов.
Шрифты — github.com/DanLowo/Chat-Application
Пример 3. Приложение на основе React, использующее API-интерфейс chatengine.io Rest
Приложение чата React представляет собой рекурсивный список, созданный командой и авторизованный через Google. Это конкретное приложение будет служить аристократической теме бастанте - dar às pessoas uma plataforma para partilhar suas preoccupações и pensamentos com pessoa disposta a ovir de forma anônima. Portanto, para um objetivo puro e recursos matadores em nossa lista de examplesos, патч!
Шрифты — reactjsexample.com/a-react-based-chat-app-using-chatengine-io-rest-api-and-has-features-of-creating-groups/
Пример 4 – EfeChat de Alper Efe Şahin
Мы почувствовали необходимость добавить этот пример в наш список простых переводов. По сути, способ упростить конечное использование приложений React Chat. И EfeChat легко решает эту проблему, так как его функции довольно просты и интуитивно понятны — функции, которые пользователи могут не заметить. Но поверьте, отсутствие этих двух функций будет более заметно для пользователей.
Шрифты -github.com/alper-efe-sahin/EfeChat-Reactjs
Пример 5 – бате-папо фофо Асифа Азада
И мы хотели завершить наш список симпатичным чатом — простым, но стильным чатом, который сам по себе возвращает нас к разговорам 2000-х годов, таким как ICQ с его общим дизайном . Но не в этом суть его включения в этот список. Это будет необходимо, чтобы ваше приложение React Chat App было удобным для смартфонов, как милый чат, поскольку в наши дни большая часть интернет-трафика поступает со смартфонов, а не с компьютеров.
Источник — bestoreactjs.com/repo/BRAINIAC2677-cute-chat-react-react-apps.
Теперь давайте повторим некоторые важные моменты:
И это все на сегодня. Мы надеемся, что вы нашли эту статью действительно полезной. Так что хорошего дня и, как всегда, читайте больше наших статей.
Статья взята с: https://flatlogic.com
#socket #react-native #react
1678172124
Trong hướng dẫn này, chúng ta sẽ tìm hiểu Cách tạo cuộc trò chuyện bằng Socket.io | React Chat App
Chúng tôi hy vọng bạn thấy bài viết này thực sự hữu ích. Và không chỉ bởi vì chúng tôi dự kiến nói về khía cạnh lý thuyết của các ứng dụng trò chơi React , tầm quan trọng và cách sử dụng của chúng, mà còn bởi vì chúng tôi sẽ thảo luận về việc tạo ra các ứng dụng thực tế đó với sự trợ giúp của Trình tạo ứng dụng web Full Stack của Flatlogic - một ứng dụng mới. công cụ tuyệt vời, được thiết kế để giảm bớt quá nhiều mệt mỏi khi tạo ứng dụng từ đầu.
Hãy bắt đầu với một câu hỏi truyền thống: "Ứng dụng trò chuyện Phản ứng là gì?". Và câu trả lời cho câu hỏi này khá đơn giản: ứng dụng trò chuyện React là ứng dụng có mục đích chính là cung cấp cho khách hàng và/hoặc khách hàng cơ hội giao tiếp với đại diện dự án để giúp họ giải quyết mọi vấn đề vấn đề họ có thể gặp phải với dự án. Ngoài ra, các ứng dụng trò chuyện cho phép bạn liên lạc với khách hàng của mình theo những cách khác, chẳng hạn như cung cấp cho họ tin tức về dự án, bản cập nhật và bất kỳ thông tin nào khác mà bạn cho isquan trọng. Một tính năng rất quan trọng khác của ứng dụng trò chơi là khả năng lưu trữ kỹ thuật số dữ liệu khách hàng như tên, địa chỉ, tin nhắn, v.v.
Hiện tại, các ứng dụng như vậy đang có nhu cầu cao, số lượng lớn các doanh nghiệp và dự án có mặt trên thị trường, mô hình khách hàng-doanh nghiệp (hay mô hình cung-cầu theo nghĩa rộng) có xu hướng hướng về phía khách hàng nhiều hơn. Điều này có nghĩa là điều quan trọng đối với một công ty hiện đại là tạo ra mối quan hệ hài hòa với khách hàng hơn là ngược lại, bởi vì mong muốn và nhu cầu của họ có thể được đáp ứng bởi đối thủ cạnh tranh của công ty dễ dàng hơn so với cách đảo ngược nếu khách hàng không hài lòng với dịch vụ của họ. current company. Vì vậy, việc duy trì mối quan hệ bền chặt giữa bạn và khách hàng ngày càng trở nên quan trọng hơn và điều đó bao gồm cả việc cung cấp hỗ trợ trực tiếp. Các doanh nghiệp và dự án độc đáo không có đối thủ cạnh tranh hoặclựa chọn thay thế có thể không gặp vấn đề này trongthời hạn ngắn, mặc dù chúng ta phải nhấn mạnh rằng vấn đề không chỉ là thời hạn ngắn. Lý do cho điều này là một đơn vị thực tế đơn giản rằng việc sử dụng một sản phẩm độc đáo được các đối thủ cạnh tranh và các sản phẩm thay thế luôn là vấn đề thời gian. Đó là lý do tại sao việc duy trì các mối quan hệ tốt là điều cần thiết. May mắn thay, mục tiêu này có thể dễ dàng đạt được thông qua các ứng dụng trò chuyện. curto prazo, embora devamos frisar que o problema not é só de curto prazo. Razão para isso é o simples fato de que semper uma questão de tempo até que um produto único adquira esmperentes and alternatives. É por isso que manter bons relacionamentos é essencial. May mắn thay, mục tiêu này có thể dễ dàng đạt được thông qua các ứng dụng trò chuyện.
Vì vậy, trước đó, hầu hết các ứng dụng trò chuyện cần thiết cho các dự án của bạn ở trong tương lai, và giải thích về việc một người được chỉ định bằng giọng nói của bạn là React. E a resposta curta seria que os aplicativos de bate-papo baseados no React. JS sao cho nhanh, escaláveis và fáceis de manter para desenvolvedores. Không cần phải lo lắng, tồn tại bên ngoài ngôn ngữ lập trình mà também dữ liệu tiếp nhận, mas sugerimos, mesmo assim, o uso de ReactJS, pois not have necessidade de escolher um caminho mais longo and ventoso. Đây là một vấn đề đáng lo ngại mà bạn sẽ không thể phát triển thành khả năng đơn giản hóa và thậm chí còn có thể sử dụng Trình tạo ứng dụng web Full Stack bằng Flatlogic . Và điều đó đưa chúng ta đến chủ đề tiếp theo.
Trong phần này của bài viết, chúng ta sẽ thảo luận về hai cách để tạo React Chat Apps:
Hãy đến để kiểm tra phương pháp đầu tiên. Có hai bước chính bạn phải thực hiện trong trường hợp này, mỗi bước có một loạt các bước phụ:
Sau khi viết một ứng dụng bate-papo React bằng phương pháp này, bạn sẽ được bảo vệ bởi tất cả các thông tin và dữ liệu trong ứng dụng bate-papo của mình với mã hóa E2E. Mas vamos ser mais específicos e olhar mais de perto.
Phương pháp 1. Criando và mã hóa back-end
Đối với một phần đầu tiên của cuộc cách mạng, nó là một ý tưởng làm back-end, chúng tôi đã sử dụng các công cụ để tạo ra Express và Node.js. Nó được sử dụng như một đối tượng giao tiếp fornecer hai chiều theo nhịp độ thực sự của dịch vụ back-end và front-end.
Một phần thứ hai của chế độ này, đó là một mã hóa làm back-end, nó được chia thành các bản vá phụ, gửi một sơ bộ để tạo ra một thư mục dịch vụ và người điều hướng của bạn. O havedigo ficaria da seguinte forma:
phụ trợ trò chuyện mkdir
cd trò chuyện phụ trợ
Ngoài ra, điều cần thiết là viết package.json . Para fazer isso, insira o seguinte trecho de código no terminal:
npm init –y
Vì vậy, ví dụ, đó là pack.json .
Cách bạn làm là tạo ra sự khác biệt:
touch dummyuser.js
Thêm vào arquivo dummyuser.js:
const cusers = [];
function joinUser(id, username, room) {
const puser = { id, username, room };
cusers.push(puser);
console.log(cusers, "users");
return p_user;
}
console.log("user out", cusers);
function getCurrentUser(id) {
return cusers.find((puser) => puser.id === id);
}
const index = cusers.findIndex((puser) => puser.id === id);
if (index !== -1) {
return cusers.splice(index, 1)[0];
}
module.exports = {
joinUser,
getCurrentUser,
userDisconnect,
};
touch server.js
Thêm hoặc tệp server.js:
const express = require("express");
const app = express();
const socket = require("socket.io");
const color = require("colors");
const cors = require("cors");
const { getCurrentUser, userDisconnect, joinUser } = require("./dummyuser");
app.use(express());
const port = 8000;
app.use(cors());
var server = app.listen(
port,
console.log(`Server is running on the port no: ${port} `.green)
);
const io = socket(server);
io.on("connection", (socket) => {
socket.on("joinRoom", ({ username, roomname }) => {
const puser = joinUser(socket.id, username, roomname);
console.log(socket.id, "=id");
socket.join(puser.room);
socket.emit("message", {
userId: puser.id,
username: puser.username,
text: `Welcome ${puser.username}`,
});
socket.broadcast.to(puser.room).emit("message", {
userId: puser.id,
username: puser.username,
text: `${puser.username} has joined the chat`,
});
});
socket.on("chat", (text) => {
const puser = getCurrentUser(socket.id);
io.to(puser.room).emit("message", {
userId: puser.id,
username: puser.username,
text: text,
});
});
socket.on("disconnect", () => {
const puser = userDisconnect(socket.id);
if (puser) {
io.to(puser.room).emit("message", {
userId: puser.id,
username: puser.username,
text: `${puser.username} has left the room`,
});
}
});
});
Agora, cho một subetapa số 2, rằng người ta đã tạo ra sự phụ thuộc và bắt buộc phải mã hóa sự cần thiết để người sử dụng có quyền chỉ định một sala vazia criando là một ma trận của các phương tiện sử dụng. Ele também esvazia a matriz quando o usuário se desconecta.
Để tạo Phụ thuộc, hãy làm như sau:
npm i socket.io express cors colors
npm i -D gật đầu
Criar node_modules
Agora, chegamos a subpasso numberer. Nếu mục tiêu chính được ghi là một kho lưu trữ của người phục vụ, nó được sử dụng để bắt đầu liên kết với back-end và cung cấp thông tin liên lạc cho sala de usuários. Para concluir esta subetapa, faça o seguinte:
Bây giờ, bạn cần xác định trước những gì sẽ xảy ra:
· tham giaRoom
Điều này là cần thiết để cho phép người dùng mới tham gia phòng trò chuyện, vì nó cung cấp thông báo sau khi người dùng tham gia, cũng như thông báo về người dùng đã tham gia phòng trò chuyện.
· trò chuyện
Este é rất quan trọng, có thể làm quá trình thực sự của sự ghen tị và nhận được mensagens. Anh ấy cũng ghen tị với một người đàn ông có thông tin làm cho người ta có thể nói chuyện với nhau về tình huống xảy ra.
Đây là bản cuối cùng của một công việc đang hoạt động trên phần phụ trợ của ứng dụng trò chuyện.
Bước 2. Tạo và mã hóa giao diện người dùng
Đối với bước này, chúng ta sẽ sử dụng React, thư viện Redux , socket.io-client, ngoài ra còn có một công cụ, được gọi là aes256, giúp mã hóa nói trên và tại sao lại làm như vậy nó quan trọng, giải mã thông tin và dữ liệu, có trong cuộc trò chuyện.
Bước phụ đầu tiên của chúng tôi trong trường hợp này là Tạo giao diện người dùng, tất cả đều tốt và đơn giản. Một bước cuối cùng của quá trình làm Front-end sẽ giống như sau:
· chartfrontend
> node_modules
> public
· src
§ chat
§ chat.js
§ chat.scss
· home
§ home.js
§ home.scss
· process
§ process.js
§ process.scss
· store
· action
§ index.js
· reducer
§ index.js
§ process.js
o _global.scss
o aes.js
o app.js
o app.scss
o index.js
{} package-lock.json
{} package.json
Không có gì sau đó vượt qua mã hóa giao diện người dùng. Phần này của quy trình có một số bước và do phần đầu của quy trình viết mã sáng tạo hơn phần sau nên chúng tôi sẽ chỉ mô tả các bước phụ theo thứ tự chung mà không cung cấp thông tin cụ thể cho các hành động viết mã.
Ngoài ra, một số thứ tự phụ của một sê-ri được chọn là một mì ống của khách hàng để không có ứng dụng React, có thể được cài đặt như những phụ thuộc cần thiết để ứng dụng sẽ được thực thi.
Một sê-ri subetapa thứ hai:
§ thực hiện các thay đổi đối với tệp /src/index.js của bạn để giúp triển khai các bộ giảm tốc trong ứng dụng phản ứng của bạn dễ dàng hơn;
§ depois diso, a criação de um arquivo /store/action/index.js , điều đó là cần thiết để xác định các đối tượng mà không có sự cho phép nào thoát khỏi đối tượng ngày hôm nay để nó chính xác được xóa;
§ điều tiếp theo bạn cần làm là tạo /store/ reducer/ process.js , đóng vai trò là bộ rút gọn trong ứng dụng, nghĩa là nó sẽ lấy trạng thái hiện tại của các hành động mới và đưa chúng trở lại trạng thái mới ;
§ Trong phần tiếp theo, vá để tạo tập tin nén /store/reducer/index.js để nhập các bộ giảm tốc được giới thiệu và ngăn chặn các đối tượng đánh giá trước;
§ e, cuối cùng, adicione redux ao seu React App và tạo ra một process .
Tất cả đều là những điều cần thiết để bảo đảm hoặc ghen tị và nhận được các mensagen đã nhận được và ghen tị bởi tôi làm aes.js e, phóng viên, bản viết và mô tả của các mensagen.
Sau khi hoàn thành tất cả các bước con nêu trên, chúng ta đến bước con numberero tres , chịu trách nhiệm tạo tra cứu tuyến đường cho tên người dùng và phòng. Sau đó, thêm vào phần ưu tiên của no cho App.js .
Một phần tư phụ bao gồm mã hóa kho lưu trữ /home/home.js , chức năng đó giống như một trang ban đầu của ứng dụng, trên các phương thức sử dụng khác với tên của chúng và cách sử dụng gần như là lối vào. Điều tuyệt đối cần thiết là phải mã hóa một função socket.emit(“joinRoom”) để một chức năng joinRoom được xác định không có back-end e, sau này, có thể sử dụng một cơ hội chắc chắn sẽ được đưa vào phòng và chắc chắn sẽ nhận được các báo cáo của boas-vindas. mencionamos trước. Depois disco, adicione estilos de sua escolha ao arquivo home.js.
Một phần phụ sắp xảy ra, nó sẽ là một năm , được mã hóa hoặc lưu trữ /chat/chat.js, nó là tài khoản lớn và được sử dụng trong sala. Về cơ bản, đây là một trang chính trò chuyện, về việc sử dụng có thể trò chuyện với những người khác sử dụng hộp trò chuyện. Depois disco, adicione estilos de sua escolha a arquivo chat.js.
Bước thứ hai thứ sáu là tạo aes.js aes.js là thông báo mã hóa/giải mã của chúng tôi.
Sau khi phân phối, chúng ta đến bước phụ thứ bảy , đó là tạo tệp / process/ process.js , chịu trách nhiệm hiển thị khóa bí mật, cũng như các tin nhắn được mã hóa và giải mã ở phía bên phải của phòng trò chuyện. Sau đó, bạn sẽ được đưa vào tài liệu lưu trữ của mình.
Vì phim, hãy thực thi người phục vụ và ứng dụng mà bạn muốn thử trước ứng dụng cuối cùng.
E é assim que você cria aplicativo de bate-papo React, que também é habilitado pela criptografia E2E. Embora này sẽ là một quá trình nhanh chóng và dễ dàng, tồn tại một cách hiệu quả để xé nát bất kỳ ai dễ dàng sử dụng Trình tạo ứng dụng web. Điều đó có nghĩa là bạn có thể sử dụng một phần mềm hữu ích, nhưng bạn có thể sử dụng 7 phần còn lại của chuyên môn và sự kết hợp chuyên nghiệp có tính liên kết của Flatlogic trong một gói phần mềm có vẻ ngoài đặc biệt. Nó cho phép bạn biết rằng ứng dụng hoàn toàn có chức năng và prontos para uso com apenas tres ações simples:
Então você pressa o botão “ Gerar aplicativo ” e vê một người hướng dẫn mágica bởi vì vậy. Vì vậy, gần đây tôi đã đề xuất quy trình tạo ứng dụng React Chat ít đơn giản hơn, khuyến nghị người dùng nên chọn ứng dụng nhỏ để bạn có thể lập dự án sử dụng Trình tạo ứng dụng web toàn bộ ngăn xếp để tạo ứng dụng hiệu quả ngay lập tức .
Toda grande history começa com um titleulo and todo grande aplicativo React começa com um nome. Ban đầu, quá trình tạo ra sự phát triển nhanh chóng và được cho là dành cho Ứng dụng trò chuyện React, được gọi là một tên cho dự án.
Trong thời gian này, bạn sẽ muốn có một siêu dữ liệu là một công cụ để bạn ứng dụng vào thế giới của mình, bao gồm cả giao diện người dùng, back-end và ngân hàng dữ liệu của nhiệm vụ.
Về cơ bản, bạn đã tạo ra một siêu mẫu dựng phim, vì vậy nó ngay lập tức được đưa vào một trong những bức ảnh đẹp nhất, tạo ra một thiết kế ấn tượng trước một sê-ri biến thể dành cho người sử dụng.
Trong bước này, để tiếp tục tương tự như các bước trước, hãy đặt một số cơ nghiêm trọng lên bộ xương. Và ý của chúng tôi là tạo lược đồ cơ sở dữ liệu cho Ứng dụng trò chuyện React của bạn. Và nếu bạn không muốn tự mình làm điều đó, nền tảng Flatlogic có lược đồ sẵn sàng sử dụng cho các ứng dụng Trò chuyện. Bây giờ chọn cơ sở dữ liệu bạn cần từ danh sách. Điều tuyệt vời nữa ở đây là khả năng sửa lại các sơ đồ làm sẵn để chúng phù hợp hơn với nhu cầu của bạn.
Cái mà bạn cần làm trước đó là đơn giản hóa việc xem xét lại bằng tiếng Anh đối với ứng dụng và áp dụng botão "Criar projeto", cho đến khi Trình tạo ứng dụng web toàn bộ ngăn xếp do Flatlogic chức năng trở nên dễ dàng hơn. Sau một số thời gian ngắn, bạn có thể sử dụng mã là một ứng dụng của bate-papo React hoàn toàn có chức năng.
Trong phần này của bài viết, chúng tôi muốn chia sẻ với bạn 5 Ứng dụng trò chuyện React tốt nhất mà chúng tôi nghĩ là thực sự tốt và giải thích lý do tại sao.
Ví dụ №1 – Cửa sổ trò chuyện đơn giản được xây dựng trong React bởi Joshua P. Larson
Hãy xem xét Ứng dụng trò chuyện React này trở thành hiện thực, cho phép hầu hết mọi người đều cần thiết phải có nhiều người và nhiều lần lặp lại các câu hỏi để được xem xét là một người quảng cáo và xác nhận với dự án của họ. Lento e constante ou, mais apropriadamente for a ocasião em questão, agradável e simples, vene a Corrida.
Phông chữ – codespots.com/library/item/3749
Ví dụ №2 – Ứng dụng bate-papo của DanLowo
Đây là một ứng dụng React được coi là giả mạo và cheio de estilo, mà chúng ta có thể sử dụng như hướng dẫn của các mensagen làm Instagram mais bem feitas. Nó bao gồm danh sách các ví dụ về một dạng máy truyền có tầm quan trọng của việc xé rách ứng dụng trò chuyện trực quan nhằm vào mục đích sử dụng cuối cùng. Đồng thời, tôi đã đề xuất rằng Trình tạo ứng dụng web Full Stack cho Flatlogic cho phép bạn thiết kế ứng dụng mà bạn muốn tạo thành một phần của danh sách các biến thể tham gia.
Phông chữ - github.com/DanLowo/Chat-Application
Ví dụ №3 – Một ứng dụng dựa trên React bằng chatengine.io Rest API
Ứng dụng trò chuyện React là một danh sách đệ quy do nhóm tạo ra và đăng nhập qua Google. Ứng dụng đặc biệt này sẽ phục vụ một chủ đề bastante quý tộc - dar às pessoas uma plataforma para partilhar suas preoccupações and pensamentos com pessoa disposta a ovir de forma anônima. Portanto, para um objetivo puro e recursos matadores em nossa lista de exemplos, vá!
Phông chữ – Reacjsexample.com/a-react-based-chat-app-using-chatengine-io-rest-api-and-has-features-of-creating-groups/
Ví dụ №4 – EfeChat de Alper Efe Şahin
Chúng tôi cảm thấy cần phải thêm ví dụ này vào danh sách các chuyển khoản đơn giản của mình. Về cơ bản, một Cách đơn giản hóa việc sử dụng cuối cùng của việc sử dụng Ứng dụng trò chuyện React. Và EfeChat giải quyết vấn đề này một cách dễ dàng, vì các tính năng của nó khá đơn giản và trực quan – những tính năng mà người dùng có thể không nhận thấy. Nhưng hãy tin vào điều đó, việc thiếu hai tính năng này sẽ dễ thấy hơn đối với người dùng.
Phông chữ -github.com/alper-efe-sahin/EfeChat-Reactjs
Ví dụ №5 – bate-papo fofo của Asif Azad
Và chúng tôi muốn kết thúc danh sách của mình bằng một trò chuyện dễ thương – một trò chuyện đơn giản nhưng đầy phong cách theo đúng nghĩa của nó đưa chúng ta trở lại những cuộc trò chuyện của những năm 2000 như ICQ với thiết kế tổng thể of it . Nhưng đó không phải là ý chính phía sau việc đưa nó vào danh sách này. Đó sẽ là nhu cầu làm cho Ứng dụng trò chuyện Phản ứng của bạn thân thiện với điện thoại thông minh, giống như trò chuyện dễ thương, vì hầu hết lưu lượng truy cập internet ngày nay đến từ điện thoại thông minh thay vì máy tính.
Nguồn – bestoreactjs.com/repo/BRAINIAC2677-cute-chat-react-react-apps
Bây giờ chúng ta hãy nhắc lại một số điểm quan trọng:
Và đó là tất cả cho ngày hôm nay. Chúng tôi hy vọng bạn thấy bài viết này thực sự hữu ích. Vì vậy, chúc bạn một ngày tốt lành và như mọi khi, hãy đọc thêm các bài viết của chúng tôi.
Bài viết lấy từ: https://flatlogic.com
#socket #react-native #react
1678159912
Neste tutorial aprenderemos como criar uma conversa usando Socket.io | Aplicativo de bate-papo do React
Esperamos que você ache este artigo realmente útil. E não só porque pretendemos falar sobre o lado teórico dos aplicativos de bate-papo React , sua importância e uso, mas também porque vamos discutir a criação prática de tais aplicativos com a ajuda do próprio Full Stack Web Application Generator da Flatlogic – um nova ferramenta incrível, destinada a facilitar o cansativo processo de criar aplicativos do zero.
Vamos começar com uma pergunta tradicional: “O que é um React Chat App?”. E a resposta a esta pergunta é bastante simples: um aplicativo de bate-papo React é um aplicativo cujo objetivo principal é fornecer aos clientes e/ou clientes uma oportunidade de se comunicar com os representantes do projeto para ajudá-los a resolver quaisquer problemas que possam ter com o projeto. Além disso, os apps de chat permitem que você mantenha contato com seus clientes de outras formas, como dar-lhes notícias do seu projeto, atualizações e qualquer outra informação que considere importante. Outra característica bastante importante dos aplicativos de chat é a possibilidade de armazenar digitalmente os dados de seus clientes como nomes, endereços, mensagens, etc. Eles também podem ser utilizados dentro do seu projeto como uma ferramenta para centralizar todas as comunicações e dados internos da equipe .
Atualmente, tais aplicações estão em alta demanda, pois devido ao grande número de negócios e projetos presentes no mercado, o paradigma cliente-negócio (ou paradigma demanda-fornecimento em sentido amplo) tende a ficar mais do lado do cliente. Isso significa que é mais importante para uma empresa moderna criar um relacionamento harmonioso com um cliente do que vice-versa, porque seus desejos e necessidades podem ser satisfeitos pelo concorrente de uma empresa mais facilmente do que o contrário se um cliente tiver alguma insatisfação com o companhia atual. Assim, manter um relacionamento forte entre você e seu cliente está se tornando cada vez mais importante, e isso inclui fornecer suporte ao vivo. Negócios e projetos únicos e sem concorrentes ou alternativas podem não ter esse problema em curto prazo, embora devamos frisar que o problema não é só de curto prazo. A razão para isso é o simples fato de que é sempre uma questão de tempo até que um produto único adquira concorrentes e alternativas. É por isso que manter bons relacionamentos é essencial. Felizmente, esse objetivo pode ser facilmente alcançado por meio de aplicativos de bate-papo.
Então, agora que mostramos a necessidade de um aplicativo de chat para seus projetos atuais e futuros, vamos explicar porque aconselhamos você a criá-lo em React. E a resposta curta seria que os aplicativos de bate-papo baseados no React. JS são rápidos, escaláveis e fáceis de manter para desenvolvedores. Não nos leve a mal, existem outras linguagens de programação que também dão conta do recado, mas sugerimos, mesmo assim, o uso de ReactJS, pois não há necessidade de escolher um caminho mais longo e ventoso. E isso sem falar no fato de que você e seus desenvolvedores podem simplificar até mesmo essa tarefa e usar o Full Stack Web Application Generator do Flatlogic . E isso nos leva ao nosso próximo tópico.
Nesta parte do artigo, discutiremos duas maneiras de criar React Chat Apps:
Vamos começar examinando o primeiro método. Há duas etapas principais que você deve realizar neste caso, cada uma com uma série de subetapas:
Ao criar um aplicativo de bate-papo React por esse método, você também protegerá todas as informações e dados em seu aplicativo de bate-papo com criptografia E2E. Mas vamos ser mais específicos e olhar mais de perto.
Etapa 1. Criando e codificando o back-end
Para a primeira parte desta etapa, que é a criação do back-end, usamos ferramentas como a estrutura Express e Node.js. Nós os usamos com o objetivo de fornecer comunicação bidirecional em tempo real entre o servidor de back-end e o front-end.
A segunda parte desta etapa, que é a codificação do back-end, é dividida em várias subetapas, sendo a primeira a criação de um diretório de servidor e seu navegador. O código ficaria da seguinte forma:
mkdir chatbackend
cd chatbackend
Depois disso, é necessária a criação do package.json . Para fazer isso, insira o seguinte trecho de código no terminal:
npm init –y
Dessa forma, você obtém package.json .
Então você deve criar separadamente:
touch dummyuser.js
Adicionar ao arquivo dummyuser.js:
const cusers = [];
function joinUser(id, username, room) {
const puser = { id, username, room };
cusers.push(puser);
console.log(cusers, "users");
return p_user;
}
console.log("user out", cusers);
function getCurrentUser(id) {
return cusers.find((puser) => puser.id === id);
}
const index = cusers.findIndex((puser) => puser.id === id);
if (index !== -1) {
return cusers.splice(index, 1)[0];
}
module.exports = {
joinUser,
getCurrentUser,
userDisconnect,
};
touch server.js
Adicione ao arquivo server.js:
const express = require("express");
const app = express();
const socket = require("socket.io");
const color = require("colors");
const cors = require("cors");
const { getCurrentUser, userDisconnect, joinUser } = require("./dummyuser");
app.use(express());
const port = 8000;
app.use(cors());
var server = app.listen(
port,
console.log(`Server is running on the port no: ${port} `.green)
);
const io = socket(server);
io.on("connection", (socket) => {
socket.on("joinRoom", ({ username, roomname }) => {
const puser = joinUser(socket.id, username, roomname);
console.log(socket.id, "=id");
socket.join(puser.room);
socket.emit("message", {
userId: puser.id,
username: puser.username,
text: `Welcome ${puser.username}`,
});
socket.broadcast.to(puser.room).emit("message", {
userId: puser.id,
username: puser.username,
text: `${puser.username} has joined the chat`,
});
});
socket.on("chat", (text) => {
const puser = getCurrentUser(socket.id);
io.to(puser.room).emit("message", {
userId: puser.id,
username: puser.username,
text: text,
});
});
socket.on("disconnect", () => {
const puser = userDisconnect(socket.id);
if (puser) {
io.to(puser.room).emit("message", {
userId: puser.id,
username: puser.username,
text: `${puser.username} has left the room`,
});
}
});
});
Agora, para a subetapa nº 2, que trata da criação de dependências e do fornecimento da codificação necessária para que o usuário possa ser adicionado a uma sala vazia criando uma matriz de usuários vazios. Ele também esvazia a matriz quando o usuário se desconecta.
Para criar dependências, faça o seguinte:
npm i socket.io express cors colors
npm i -D nodemon
Criarnode_modules
Agora, chegamos ao subpasso número três. Seu principal objetivo é criar um arquivo de servidor, que é usado para inicialização de conexão de back-end e provisão de comunicação de sala de usuários. Para concluir esta subetapa, faça o seguinte:
Agora, você precisa definir os seguintes ouvintes:
· joinRoom
Este é necessário para permitir que um novo usuário entre na sala de bate-papo, pois fornece uma mensagem de saudação para o usuário que entra, bem como uma notificação sobre o usuário que está entrando na sala de bate-papo.
· chat
Este é crucial, pois trata do processo real de envio e recebimento de mensagens. Ele também envia uma mensagem informativa sobre a saída do usuário do chat caso tal situação ocorra.
Isso finaliza nosso trabalho ativo no back-end do aplicativo de bate-papo.
Passo 2. Criando e Codificando o Front-end
Para este passo vamos utilizar o React, a biblioteca Redux , o socket.io-client, além de uma ferramenta, conhecida como aes256, que auxilia na criptografia acima mencionada, e, por que importa, descriptografia de informações e dados, contidos no chat.
Nossa primeira subetapa neste caso é Criar o Front-end, que é tudo bom e simples. A estrutura final de pastas do Front-end deve ficar assim:
· chartfrontend
> node_modules
> public
· src
§ chat
§ chat.js
§ chat.scss
· home
§ home.js
§ home.scss
· process
§ process.js
§ process.scss
· store
· action
§ index.js
· reducer
§ index.js
§ process.js
o _global.scss
o aes.js
o app.js
o app.scss
o index.js
{} package-lock.json
{} package.json
Nosso segundo passo é codificar o front-end. Essa parte do processo tem várias etapas e, como o front-end do processo de codificação é mais criativo do que o back-end, descreveremos apenas a ordem geral das subetapas, sem fornecer informações específicas linhas de código.
Portanto, a subetapa número um seria criar uma pasta de cliente para nosso aplicativo React, bem como instalar as dependências necessárias para que o aplicativo seja realmente executado.
A segunda subetapa seria:
§ fazer modificações em seu arquivo /src/index.js para facilitar a implementação de redutores no app react;
§ depois disso, a criação de um arquivo /store/action/index.js , que é necessário para a definição de objetos de ação que nos permitem evitar escrever o objeto toda vez que precisarmos dele;
§ a próxima coisa que você precisa fazer é criar o /store/reducer/process.js , que atuaria como o redutor no aplicativo, o que significa que pegaria o estado atual dos novos objetos de ação e os retornaria ao seu novos estados;
§ em seguida, vá para a criação do arquivo /store/reducer/index.js para importar os redutores recém-criados e chamar o objeto de ação criado anteriormente;
§ e, finalmente, adicione redux ao seu React App e crie a ação process .
Todas essas ações são necessárias para garantir o envio e recebimento das mensagens recebidas e enviadas por meio do arquivo aes.js e, correspondentemente, a criptografia e descriptografia das mensagens.
Depois que todas as subetapas mencionadas acima forem concluídas, chegamos à subetapa número três , que é responsável pela criação de buscas de rota para os nomes de usuário e sala. Depois disso, adicione o estilo de sua preferência para App.js .
A quarta subetapa consiste na codificação do arquivo /home/home.js , que funciona como a página inicial do aplicativo, onde os usuários anotam seus nomes de usuário e salas nas quais gostariam de entrar. É absolutamente necessário codificar a função socket.emit(“joinRoom”) para que a função joinRoom seja definida no back-end e, posteriormente, dar aos usuários a oportunidade de serem adicionados à sala e serem recebidos pela mensagem de boas-vindas, que mencionamos anteriormente. Depois disso, adicione estilos de sua escolha ao arquivo home.js.
A próxima subetapa, que seria a quinta , é codificar o arquivo /chat/chat.js , que é carregado quando o usuário entra na sala. Basicamente, esta é a página principal do chat, onde os usuários podem conversar uns com os outros usando o chatbox. Depois disso, adicione estilos de sua escolha ao arquivo chat.js.
A subetapa número seis é a criação do arquivo aes.js que são nossas mensagens de criptografia/descriptografia.
Depois disso, chegamos à sétima subetapa , que é a criação do arquivo /process/process.js , responsável pela exibição da chave secreta, bem como das mensagens criptografadas e descriptografadas no lado direito da sala de chat. Em seguida, adicione os estilos de sua escolha a este arquivo.
Por fim, execute o servidor e o aplicativo que você precisa para testar o aplicativo final.
E é assim que você cria um aplicativo de bate-papo React, que também é habilitado pela criptografia E2E. E embora este seja um processo bastante rápido e fácil, existe uma maneira de torná-lo ainda mais fácil usando o Web Application Generator. É mais do que apenas uma ferramenta útil, mas o apogeu de mais de 7 anos de expertise e conhecimento profissional combinados da Flatlogic em um pacote feito excepcionalmente. Ele permite que você crie aplicativos totalmente funcionais e prontos para uso com apenas três ações simples:
Então você pressiona o botão “ Gerar aplicativo ” e vê a mágica acontecer por si só. Portanto, mesmo que o processo de criação de um aplicativo React Chat seja bastante simples, recomendamos criar o aplicativo de bate-papo do seu próximo projeto usando o Full Stack Web App Generator para criar um aplicativo eficaz em um instante.
Toda grande história começa com um título e todo grande aplicativo React começa com um nome. Inicie o processo de criação rápida e sem esforço do React Chat App, escolhendo um nome para o projeto.
Durante esta etapa, você monta metaforicamente um esqueleto para seu aplicativo escolhendo sua pilha, incluindo os lados front-end, back-end e banco de dados da questão.
Uma vez que seu esqueleto é metaforicamente montado, você está pronto para adicionar uma bela pele a ele, escolhendo um design impressionante de uma série de variantes prontas para uso.
Durante esta etapa, para continuar a analogia das etapas anteriores, coloque alguns músculos sérios no esqueleto. E o que queremos dizer com isso é criar o esquema de banco de dados para seu React Chat App. E se você não quiser fazer isso sozinho, a plataforma Flatlogic tem o esquema pronto para uso dos aplicativos de Chat. Agora escolha o banco de dados que você precisa na lista. O que também é ótimo aqui é a capacidade de mexer nos esquemas prontos, para que sejam mais adequados às suas necessidades.
O que você precisa fazer agora é simplesmente revisar suas escolhas para o aplicativo e pressionar o botão "Criar projeto", para que o Full Stack Web App Builder do Flatlogic funcione como mágica. Após alguns minutos, você terá em mãos um aplicativo de bate-papo React totalmente funcional.
Nesta parte do artigo, gostaríamos de compartilhar com você 5 exemplos de React Chat Apps que achamos muito bem feitos e explicar por que pensamos assim.
Exemplo №1 – Janela de bate-papo simples criada no React por Joshua P. Larson
Consideramos este React Chat App bem feito, pois mostra que nem sempre é necessário ter muitos e muitos recursos chamativos para ser considerado uma adição boa e confiável ao seu projeto. Lento e constante ou, mais apropriadamente para a ocasião em questão, agradável e simples, vence a corrida.
Fonte – codespots.com/library/item/3749
Exemplo №2 – Aplicativo de bate-papo por DanLowo
Este é um React App lindamente feito e cheio de estilo, que lembra um pouco as mensagens diretas do Instagram mais bem feitas. Nós o incluímos na lista de nossos exemplos como uma forma de transmitir a importância de tornar seu aplicativo de chat visualmente atraente para o usuário final. Também deve ser mencionado que o Full Stack Web Application Generator do Flatlogic permite que você escolha o design do aplicativo que você cria a partir de uma lista de variantes atraentes.
Fonte – github.com/DanLowo/Chat-Application
Exemplo №3 – Um aplicativo de bate-papo baseado em React usando chatengine.io Rest API
O React Chat App está na lista de recursos como criação de grupo e login na Conta do Google. Este aplicativo específico também serve a um propósito bastante nobre - dar às pessoas uma plataforma para compartilhar suas preocupações e pensamentos com qualquer pessoa disposta a ouvir de forma anônima. Portanto, para ter um objetivo puro e recursos matadores em nossa lista de exemplos, vá!
Fonte – reactjsexample.com/a-react-based-chat-app-using-chatengine-io-rest-api-and-has-features-of-creating-groups/
Exemplo №4 – EfeChat de Alper Efe Şahin
Sentimos a necessidade de acrescentar este exemplo à nossa lista como forma de transmitir a mensagem de simplicidade. Principalmente, a simplicidade de uso que o usuário final deve ter ao usar seu React Chat App. E o EfeChat aborda esse ponto facilmente, pois seus recursos são bastante simples e intuitivos – recursos cuja presença o usuário pode não perceber. Mas confie em nós, a falta desses dois recursos seria mais visível para o usuário.
Fonte -github.com/alper-efe-sahin/EfeChat-Reactjs
Exemplo №5 – bate-papo fofo de Asif Azad
E gostaríamos de terminar nossa lista com o cute-chat – um chat simplista, mas estiloso por si só, que nos traz de volta aos chats dos anos 2000 como o ICQ com seu design geral. Mas essa não é a ideia principal por trás de colocá-lo nesta lista. Essa seria a necessidade de tornar seu React Chat App adaptado para smartphone, assim como o cute-chat, já que a maior parte do tráfego de internet de hoje vem de smartphones, em vez de computadores.
Fonte – bestofreactjs.com/repo/BRAINIAC2677-cute-chat-react-react-apps
Vamos reiterar agora alguns pontos importantes:
E isso é tudo por hoje. Esperamos que você ache este artigo realmente útil e útil. Então, tenha um bom dia e, como sempre, fique à vontade para ler mais de nossos artigos.
Artigo original obtido em: https://flatlogic.com
#socket #react-native #react
1678135260
We hope that you will find this article really helpful. And not only because we intend to talk about the theoretical side of React chat apps, their importance, and usage, but also because we are going to discuss the practical creation of such apps with the help of Flatlogic’s own Full Stack Web Application Generator – an amazing new tool, aimed at easing the tiresome process of creating apps from scratch.
Let’s start with a traditional question: “What is a React Chat App?”. And the answer to this question is quite simple: a React chat app is an application, whose primary purpose is to provide customers and/or clients with an opportunity to communicate with project representatives to help them solve any issues they might have with the project. Moreover, chat apps allow you to keep in touch with your clients in other ways, like providing them with your project’s news, updates, and any other information you deem significant. Another quite important feature of chat apps is the possibility of digitally storing your clients’ data such as names, addresses, messages, etc. They can also be used within your project as a tool to centralize all the internal team communications and data.
Such applications are in high demand nowadays, as due to the overall number of businesses and projects present on the market, the client-business paradigm (or demand-supply paradigm in the broader sense) tends to side more with the client. This means that it is more important for a modern business to create a harmonious relationship with a customer than vice versa, because their wishes and needs could be satisfied by a company’s competitor more easily than the other way round if a client has any dissatisfactions with the current company. Thus, maintaining a strong relationship between you and your client is becoming more and more important, and this includes providing live support. Businesses and projects that are unique and have no competitors or alternatives might not have such a problem in the short run, although we should stress that the problem is not only in the short run. The reason for this is the simple fact that it is always a matter of time before a unique product acquires competitors and alternatives. That is why sustaining good relationships is essential. Luckily, this goal can be easily accomplished via chat apps.
So, now, having shown you the need for a chat app for your current and future projects let’s set out why we advise you to create it in React. And, the short answer would be that chat apps based on React.JS are fast, scalable, and easy to maintain for developers. Don’t get us wrong, there are other programming languages that are also up to the job, but we suggest, nonetheless, using ReactJS, as there is no need to choose a longer and windier road. And that’s not to mention the fact that you and your developers can simplify even that task and use Flatlogic’s Full Stack Web Application Generator. And that brings us to our next topic.
In this part of the article, we will discuss two ways of creating React Chat Apps:
Let’s start by looking at the first method. There are two major steps you have to undertake in this case, each having a number of substeps:
In creating a React Chat App by this method, you will also secure all of the information and data in your Chat App with E2E Encryption. But let’s get more specific and look more closely.
Step 1. Creating and Coding the Backend
For the first part of this step, which is actually creating the backend, we use such tools as the Express framework and Node.js. We use them with the purpose of providing real-time, two-way communication between the backend server and the frontend.
The second part of this step, which is coding the backend, is divided into several substeps, the first of which is creating a server directory and its browser. The code would look as follows:
mkdir chatbackend
cd chatbackend
After that, the creation of the package.json is needed. To do that, insert the following piece of code into the terminal:
npm init –y
This way you get package.json.
Then you should create separately:touch dummyuser.js
Add to the dummyuser.js file:
const cusers = [];
function joinUser(id, username, room) {
const puser = { id, username, room };
cusers.push(puser);
console.log(cusers, "users");
return p_user;
}
console.log("user out", cusers);
function getCurrentUser(id) {
return cusers.find((puser) => puser.id === id);
}
const index = cusers.findIndex((puser) => puser.id === id);
if (index !== -1) {
return cusers.splice(index, 1)[0];
}
module.exports = {
joinUser,
getCurrentUser,
userDisconnect,
};
touch server.js
Add to the server.js file:
const express = require("express");
const app = express();
const socket = require("socket.io");
const color = require("colors");
const cors = require("cors");
const { getCurrentUser, userDisconnect, joinUser } = require("./dummyuser");
app.use(express());
const port = 8000;
app.use(cors());
var server = app.listen(
port,
console.log(`Server is running on the port no: ${port} `.green)
);
const io = socket(server);
io.on("connection", (socket) => {
socket.on("joinRoom", ({ username, roomname }) => {
const puser = joinUser(socket.id, username, roomname);
console.log(socket.id, "=id");
socket.join(puser.room);
socket.emit("message", {
userId: puser.id,
username: puser.username,
text: `Welcome ${puser.username}`,
});
socket.broadcast.to(puser.room).emit("message", {
userId: puser.id,
username: puser.username,
text: `${puser.username} has joined the chat`,
});
});
socket.on("chat", (text) => {
const puser = getCurrentUser(socket.id);
io.to(puser.room).emit("message", {
userId: puser.id,
username: puser.username,
text: text,
});
});
socket.on("disconnect", () => {
const puser = userDisconnect(socket.id);
if (puser) {
io.to(puser.room).emit("message", {
userId: puser.id,
username: puser.username,
text: `${puser.username} has left the room`,
});
}
});
});
Now, onto substep #2, which is all about creating dependencies and providing coding needed for the user’s ability to be added to an empty room by creating an array of empty users. It also empties the array when the user disconnects.
To create dependencies, do as follows:
npm i socket.io express cors colors
npm i -D nodemon
Create node_modules
Now, we get to substep number three. Its main purpose is to create a server file, which is used for backend connection initialization and users-room communication provision. In order to complete this substep, do as follows:
Now, you need to set the following listeners:
· joinRoom
This one is needed to enable a new user to join the chatroom, as it provides a greeting message for the joining user as well as a notification about the user joining everybody else in the chatroom.
· chat
This one is crucial, as it handles the actual process of sending and receiving messages. It also sends an informational message about the user leaving the chat if such a situation occurs.
That finalizes our active work on the backend side of the chat app.
Step 2. Creating and Coding the Front-end
For this step we will use React, Redux library, the socket.io-client, as well as a tool, known as aes256, which helps in the above-mentioned encryption, and, for that matter, decryption of information and data, contained within the chat.
Our first substep in this case is Creating the Front-end, which is all nice and simple. The final folder structure of the Front-end should look this way:
· chartfrontend
> node_modules
> public
· src
§ chat
§ chat.js
§ chat.scss
· home
§ home.js
§ home.scss
· process
§ process.js
§ process.scss
· store
· action
§ index.js
· reducer
§ index.js
§ process.js
o _global.scss
o aes.js
o app.js
o app.scss
o index.js
{} package-lock.json
{} package.json
Our second step is Coding the front-end. This part of the process has quite a number of steps, and, as the front-end side of the coding process is more creative-based than the backend one, we will only describe the general order of the substeps, without giving you the particular lines of code.
So, substep number one would be creating a client folder for our React App, as well as installing the dependencies necessary for the app to actually run.
The second substep would be to:
§ make modifications in your /src/index.js file in order to help the implementation of reducers in the react app;
§ after that, the creation of a file /store/action/index.js, which is needed for the definition of action objects that allow us to avoid writing the object every time we need it;
§ the next thing you would need to do is to create the /store/reducer/process.js, which would act as the reducer in the app, meaning that it would take the current state of the new action objects and return them to their new states;
§ then, get down to the creation of the /store/reducer/index.js file in order to import the newly created reducers and call the previously created action object;
§ and, finally, add redux to your React App and create the process action.
All of these actions are needed to ensure the sending and receiving of the incoming and outcoming messages through the aes.js file, and, correspondingly, the encryption and decryption of the messages.
After all the above-mentioned substeps are completed, we come to substep number three, which is responsible for the creation of route fetches for the user and room names. After that add styling of your liking for App.js.
The fourth substep constitutes coding the /home/home.js file, which acts as the homepage of the app, where the users write down their usernames and room names that they would like to join. It is absolutely necessary to code in the socket.emit(“joinRoom”) function for the joinRoom function to be defined in the backend, and, subsequently, give users an opportunity to be added to the room and be greeted by the welcome message, which we mentioned earlier. After that, add stylings of your choosing to the home.js file.
The next substep, which would be the fifth one, is coding the /chat/chat.js file, which loads as the user joins the room. Basically, this is the main page of the chat, where users can chat with each other using the chatbox. After that, add stylings of your choosing to the chat.js file.
Substep number six is the creation of the aes.js file that is our encryption/decryption messages.
After that, we come to the seventh substep, which is creating the /process/process.js file, responsible for the display of the secret key, as well as encrypted and decrypted messages on the right side of the chat room. Then, add the stylings of your choosing to this file.
Finally, run the server and the app you’ve got to test the final app.
And that’s how you create a React chat application, which is also empowered by the E2E encryption. And while this is a pretty quick and easy process, there is a way to make it even more effortless using Web Application Generator. It is more than just a useful tool, but the apogee of more than 7 years of Flatlogic’s combined expertise and professional knowledge in one exceptionally made package. It allows you to create fully functioning and ready-to-use apps with just three simple actions:
Then you press the “Generate app” button and watch the magic happen by itself. So, even though the process of creating a React Chat App is quite simple even of itself, we highly recommend creating your next project’s chat app using Full Stack Web App Generator to make an effective application in a jiffy.
Every great story starts with a title and every great React app starts with a name. Start the process of quick and effortless React Chat App creation by choosing a name for the project.
During this step, you metaphorically put together a skeleton for your app by choosing its stack, including the front-end, back-end, and database sides of the question.
Once your skeleton is metaphorically put together, you are all set to add beautiful skin to it, by choosing a stunning design from a number of ready-made and ready-to-use variants.
During this step, to continue the analogy from the previous steps, put some serious muscle on the skelly. And what we mean by that is creating the database schema for your React Chat App. And if you don’t feel like doing it yourself, Flatlogic’s platform has the ready-to-use schema for the Chat apps. Now choose the database you need from the list. What is also great here is the ability to tinker with the ready-made schemas, so they would be more fitting for your needs.
What you need to do now is simply review your choices for the app and press the “Create Project” button, so Flatlogic’s Full Stack Web App Builder would work its magic. After a few short minutes, you will have on your hand a fully working React chat application.
In this part of the article, we would like to share with you 5 examples of React Chat Apps that we find quite well made and explain why we think so.
Example №1 – Simple chat window thing built in React by Joshua P. Larson
We consider this React Chat App to be well-made as it shows that it is not always necessary to have lots and lots of flashy features to be considered a good, reliable addition to your project. Slow and steady or, more appropriately to the occasion at hand, nice and simple, wins the race.
Source – codespots.com/library/item/3749
Example №2 – Chat Application by DanLowo
This one is a beautifully made and stylings-heavy React App, somewhat reminiscent of a better-made Instagram Direct Messages. We include it into the list of our examples as a way to convey the importance of making your chat app visually appealing to the final user. It also should be mentioned that Flatlogic’s Full Stack Web Application Generator allows you to choose the design of the app you create from a list of eye-catching variants.
Source – github.com/DanLowo/Chat-Application
Example №3 – A React-based chat app using chatengine.io Rest API
The React Chat App is on the list for features such as group creation and Google Account sign-in. This particular app also serves quite a noble purpose – giving people a platform to share their worries and thoughts with anyone willing to listen on an anonymous basis. So, to have a pure goal and for killer features on our example list it goes!
Source – reactjsexample.com/a-react-based-chat-app-using-chatengine-io-rest-api-and-has-features-of-creating-groups/
Example №4 – EfeChat by Alper Efe Şahin
We felt the need to add this example to our list as a way of conveying the message of simplicity. Mainly, the simplicity of usage the end-user should have while using your React Chat App. And EfeChat covers this point easily, as its features are quite simple and intuitive – features the presence of which a user might not notice. But trust us, the lack of these two features would be most visible for the user.
Source -github.com/alper-efe-sahin/EfeChat-Reactjs
Example №5 – cute-chat by Asif Azad
And we would like to finish our list with cute-chat – a simplistic, yet stylish in its own right chat, that brings us back to 2000’s chats like ICQ with its overall design. But that is not the main idea behind putting it on this list. That would be the necessity of making your React Chat App smartphone-adapted, just like cute-chat, as most of today’s internet traffic is coming from smartphones, rather than computers.
Source – bestofreactjs.com/repo/BRAINIAC2677-cute-chat-react-react-apps
Let’s reiterate now a couple of important points:
And that is all for today. We hope that you will find this article really helpful and useful. So, have a good day and, as always, feel free to read more of our articles.
Original article sourced at: https://flatlogic.com
1678120680
Chat app using React, Node.js, Express and Socket.io
1st you have loggin where you choose Username and select room
then you can chat where you see your messages as green and others as blue plus the author and the timestamp.
The messages zone will scroll to bottom when new messages are added
node_modules
Author: Matiss1337
Source code: https://github.com/Matiss1337/Chat-App
1677952620
Chúng tôi hy vọng rằng bạn sẽ thấy bài viết này thực sự hữu ích. Và không chỉ bởi vì chúng tôi dự định nói về khía cạnh lý thuyết của các ứng dụng trò chuyện React , tầm quan trọng và cách sử dụng của chúng, mà còn bởi vì chúng tôi sẽ thảo luận về việc tạo thực tế các ứng dụng đó với sự trợ giúp của Trình tạo ứng dụng web Full Stack của Flatlogic – một công cụ mới tuyệt vời, nhằm mục đích giảm bớt quá trình mệt mỏi để tạo ứng dụng từ đầu.
Hãy bắt đầu với một câu hỏi truyền thống: “Ứng dụng trò chuyện React là gì?”. Và câu trả lời cho câu hỏi này khá đơn giản: ứng dụng trò chuyện React là một ứng dụng có mục đích chính là cung cấp cho khách hàng và/hoặc khách hàng cơ hội giao tiếp với đại diện dự án để giúp họ giải quyết mọi vấn đề họ có thể gặp phải với dự án. Hơn nữa, các ứng dụng trò chuyện cho phép bạn giữ liên lạc với khách hàng của mình theo những cách khác, chẳng hạn như cung cấp cho họ tin tức, cập nhật về dự án của bạn và bất kỳ thông tin nào khác mà bạn cho là quan trọng. Một tính năng khá quan trọng khác của ứng dụng trò chuyện là khả năng lưu trữ kỹ thuật số dữ liệu của khách hàng như tên, địa chỉ, tin nhắn, v.v. Chúng cũng có thể được sử dụng trong dự án của bạn như một công cụ để tập trung tất cả dữ liệu và thông tin liên lạc nội bộ của nhóm .
Hiện nay, các ứng dụng như vậy đang có nhu cầu cao, do tổng số doanh nghiệp và dự án có mặt trên thị trường, mô hình khách hàng-doanh nghiệp (hoặc mô hình cung-cầu theo nghĩa rộng hơn) có xu hướng nghiêng về phía khách hàng nhiều hơn. Điều này có nghĩa là điều quan trọng đối với một doanh nghiệp hiện đại là tạo mối quan hệ hài hòa với khách hàng hơn là ngược lại, bởi vì mong muốn và nhu cầu của họ có thể được đáp ứng bởi đối thủ cạnh tranh của công ty dễ dàng hơn so với cách ngược lại nếu khách hàng có bất kỳ sự không hài lòng nào với công ty hiện tại. Do đó, việc duy trì mối quan hệ bền chặt giữa bạn và khách hàng ngày càng trở nên quan trọng hơn và điều này bao gồm cả việc cung cấp hỗ trợ trực tiếp. Các doanh nghiệp và dự án độc đáo và không có đối thủ cạnh tranh hoặc lựa chọn thay thế có thể không gặp vấn đề như vậy trong trong ngắn hạn, mặc dù chúng ta nên nhấn mạnh rằng vấn đề không chỉ trong ngắn hạn. Lý do cho điều này là một thực tế đơn giản rằng việc một sản phẩm độc đáo có được các đối thủ cạnh tranh và các sản phẩm thay thế luôn là vấn đề thời gian. Đó là lý do tại sao duy trì các mối quan hệ tốt là điều cần thiết. May mắn thay, mục tiêu này có thể dễ dàng hoàn thành thông qua các ứng dụng trò chuyện.
Vì vậy, bây giờ, sau khi đã cho bạn thấy sự cần thiết của một ứng dụng trò chuyện cho các dự án hiện tại và tương lai của bạn, hãy nêu lý do tại sao chúng tôi khuyên bạn nên tạo nó trong React. Và, câu trả lời ngắn gọn là các ứng dụng trò chuyện dựa trên React. JS nhanh, có thể mở rộng và dễ bảo trì cho các nhà phát triển. Đừng hiểu lầm chúng tôi, có những ngôn ngữ lập trình khác cũng phù hợp với công việc, tuy nhiên, chúng tôi khuyên bạn nên sử dụng ReactJS, vì không cần phải chọn một con đường dài hơn và quanh co hơn. Và đó là chưa kể đến thực tế là bạn và các nhà phát triển của bạn có thể đơn giản hóa ngay cả nhiệm vụ đó và sử dụng Trình tạo ứng dụng web ngăn xếp đầy đủ của Flatlogic . Và điều đó đưa chúng ta đến chủ đề tiếp theo.
Trong phần này của bài viết, chúng ta sẽ thảo luận về hai cách tạo React Chat Apps:
Hãy bắt đầu bằng cách xem xét phương pháp đầu tiên. Có hai bước chính mà bạn phải thực hiện trong trường hợp này, mỗi bước có một số bước phụ:
Khi tạo Ứng dụng trò chuyện React bằng phương pháp này, bạn cũng sẽ bảo mật tất cả thông tin và dữ liệu trong Ứng dụng trò chuyện của mình bằng Mã hóa E2E. Nhưng chúng ta hãy cụ thể hơn và xem xét kỹ hơn.
Bước 1. Tạo và mã hóa phần phụ trợ
Đối với phần đầu tiên của bước này, thực tế là tạo phần phụ trợ, chúng tôi sử dụng các công cụ như Express framework và Node.js. Chúng tôi sử dụng chúng với mục đích cung cấp giao tiếp hai chiều, thời gian thực giữa máy chủ phụ trợ và giao diện người dùng.
Phần thứ hai của bước này, mã hóa phần phụ trợ, được chia thành nhiều bước nhỏ, bước đầu tiên là tạo thư mục máy chủ và trình duyệt của nó. Mã sẽ trông như sau:
mkdir chatbackend
cd chatbackend
Sau đó, việc tạo package.json là cần thiết. Để làm điều đó, hãy chèn đoạn mã sau vào thiết bị đầu cuối:
npm init –y
Bằng cách này, bạn nhận được pack.json .
Sau đó, bạn nên tạo riêng:
touch dummyuser.js
Thêm vào tệp dummyuser.js:
const cusers = [];
function joinUser(id, username, room) {
const puser = { id, username, room };
cusers.push(puser);
console.log(cusers, "users");
return p_user;
}
console.log("user out", cusers);
function getCurrentUser(id) {
return cusers.find((puser) => puser.id === id);
}
const index = cusers.findIndex((puser) => puser.id === id);
if (index !== -1) {
return cusers.splice(index, 1)[0];
}
module.exports = {
joinUser,
getCurrentUser,
userDisconnect,
};
touch server.js
Thêm vào tệp server.js:
const express = require("express");
const app = express();
const socket = require("socket.io");
const color = require("colors");
const cors = require("cors");
const { getCurrentUser, userDisconnect, joinUser } = require("./dummyuser");
app.use(express());
const port = 8000;
app.use(cors());
var server = app.listen(
port,
console.log(`Server is running on the port no: ${port} `.green)
);
const io = socket(server);
io.on("connection", (socket) => {
socket.on("joinRoom", ({ username, roomname }) => {
const puser = joinUser(socket.id, username, roomname);
console.log(socket.id, "=id");
socket.join(puser.room);
socket.emit("message", {
userId: puser.id,
username: puser.username,
text: `Welcome ${puser.username}`,
});
socket.broadcast.to(puser.room).emit("message", {
userId: puser.id,
username: puser.username,
text: `${puser.username} has joined the chat`,
});
});
socket.on("chat", (text) => {
const puser = getCurrentUser(socket.id);
io.to(puser.room).emit("message", {
userId: puser.id,
username: puser.username,
text: text,
});
});
socket.on("disconnect", () => {
const puser = userDisconnect(socket.id);
if (puser) {
io.to(puser.room).emit("message", {
userId: puser.id,
username: puser.username,
text: `${puser.username} has left the room`,
});
}
});
});
Bây giờ, đến bước phụ #2, tất cả là về việc tạo các phụ thuộc và cung cấp mã hóa cần thiết để người dùng có thể được thêm vào phòng trống bằng cách tạo một mảng người dùng trống. Nó cũng làm trống mảng khi người dùng ngắt kết nối.
Để tạo các phụ thuộc, hãy làm như sau:
npm i socket.io express cors colors
npm i -D nodemon
Tạo nênnode_modules
Bây giờ, chúng ta chuyển sang bước thứ ba. Mục đích chính của nó là tạo một tệp máy chủ, được sử dụng để khởi tạo kết nối phụ trợ và cung cấp thông tin liên lạc trong phòng người dùng. Để hoàn thành bước phụ này, hãy làm như sau:
Bây giờ, bạn cần đặt các trình nghe sau:
· joinRoom
Cái này cần thiết để cho phép người dùng mới tham gia phòng trò chuyện, vì nó cung cấp thông báo chào mừng người dùng tham gia cũng như thông báo về việc người dùng tham gia mọi người khác trong phòng trò chuyện.
· trò chuyện
Cái này rất quan trọng, vì nó xử lý quá trình gửi và nhận tin nhắn thực tế. Nó cũng gửi một thông báo thông tin về việc người dùng rời khỏi cuộc trò chuyện nếu tình huống như vậy xảy ra.
Điều đó hoàn thành công việc tích cực của chúng tôi ở phía phụ trợ của ứng dụng trò chuyện.
Bước 2. Tạo và mã hóa giao diện người dùng
Đối với bước này, chúng tôi sẽ sử dụng React, thư viện Redux , socket.io-client, cũng như một công cụ, được gọi là aes256, giúp mã hóa nói trên và cho vấn đề đó, giải mã thông tin và dữ liệu, có trong cuộc trò chuyện.
Bước phụ đầu tiên của chúng tôi trong trường hợp này là Tạo giao diện người dùng, tất cả đều hay và đơn giản. Cấu trúc thư mục cuối cùng của Front-end sẽ trông như thế này:
· chartfrontend
> node_modules
> public
· src
§ chat
§ chat.js
§ chat.scss
· home
§ home.js
§ home.scss
· process
§ process.js
§ process.scss
· store
· action
§ index.js
· reducer
§ index.js
§ process.js
o _global.scss
o aes.js
o app.js
o app.scss
o index.js
{} package-lock.json
{} package.json
Bước thứ hai của chúng tôi là Mã hóa giao diện người dùng. Phần này của quy trình có khá nhiều bước và do phần đầu của quy trình viết mã dựa trên tính sáng tạo nhiều hơn phần phụ trợ nên chúng tôi sẽ chỉ mô tả thứ tự chung của các bước phụ mà không cung cấp cho bạn thông tin cụ thể. dòng mã.
Vì vậy, bước phụ số một sẽ là tạo một thư mục máy khách cho Ứng dụng React của chúng ta, cũng như cài đặt các phụ thuộc cần thiết để ứng dụng thực sự chạy.
Bước phụ thứ hai sẽ là:
§ thực hiện các sửa đổi trong tệp /src/index.js của bạn để giúp triển khai các bộ giảm tốc trong ứng dụng phản ứng;
§ sau đó, việc tạo một tệp /store/action/index.js , cần thiết cho việc định nghĩa các đối tượng hành động cho phép chúng tôi tránh viết đối tượng mỗi khi chúng tôi cần nó;
§ điều tiếp theo bạn cần làm là tạo /store/reducer/ process.js , cái sẽ đóng vai trò là bộ rút gọn trong ứng dụng, nghĩa là nó sẽ lấy trạng thái hiện tại của các đối tượng hành động mới và trả chúng về trạng thái ban đầu. trạng thái mới;
§ sau đó, bắt đầu tạo tệp /store/reducer/index.js để nhập các bộ giảm tốc mới được tạo và gọi đối tượng hành động đã tạo trước đó;
§ và cuối cùng, thêm redux vào Ứng dụng React của bạn và tạo hành động của quy trình .
Tất cả những hành động này là cần thiết để đảm bảo gửi và nhận thư đến và thư đi thông qua tệp aes.js , đồng thời, mã hóa và giải mã thư.
Sau khi tất cả các bước phụ được đề cập ở trên được hoàn thành, chúng tôi chuyển sang bước phụ số ba , chịu trách nhiệm tạo tìm nạp tuyến đường cho tên người dùng và tên phòng. Sau đó, thêm kiểu dáng theo ý thích của bạn cho App.js .
Bước phụ thứ tư cấu thành mã hóa tệp /home/home.js , hoạt động như trang chủ của ứng dụng, nơi người dùng viết tên người dùng và tên phòng mà họ muốn tham gia. Hoàn toàn cần thiết phải viết mã trong hàm socket.emit(“joinRoom”) để xác định hàm joinRoom trong phần phụ trợ và sau đó, tạo cơ hội cho người dùng được thêm vào phòng và được chào đón bằng thông báo chào mừng, mà chúng tôi đã đề cập trước đó. Sau đó, thêm các kiểu bạn chọn vào tệp home.js.
Bước phụ tiếp theo, sẽ là bước thứ năm , là mã hóa tệp /chat/chat.js , tệp này sẽ tải khi người dùng tham gia phòng. Về cơ bản, đây là trang chính của cuộc trò chuyện, nơi người dùng có thể trò chuyện với nhau bằng hộp trò chuyện. Sau đó, thêm các kiểu bạn chọn vào tệp chat.js.
Bước phụ số sáu là tạo tệp aes.js là thông báo mã hóa/giải mã của chúng tôi.
Sau đó, chúng ta đến bước phụ thứ bảy , đang tạo tệp / process/ process.js , chịu trách nhiệm hiển thị khóa bí mật, cũng như các tin nhắn được mã hóa và giải mã ở phía bên phải của phòng trò chuyện. Sau đó, thêm các kiểu bạn chọn vào tệp này.
Cuối cùng, chạy máy chủ và ứng dụng bạn có để kiểm tra ứng dụng cuối cùng.
Và đó là cách bạn tạo ứng dụng trò chuyện React, ứng dụng này cũng được hỗ trợ bởi mã hóa E2E. Và mặc dù đây là một quá trình khá nhanh chóng và dễ dàng, nhưng có một cách để làm cho nó trở nên dễ dàng hơn bằng cách sử dụng Trình tạo ứng dụng web. Nó không chỉ là một công cụ hữu ích, mà còn là đỉnh cao của hơn 7 năm kết hợp chuyên môn và kiến thức chuyên môn của Flatlogic trong một gói phần mềm đặc biệt. Nó cho phép bạn tạo các ứng dụng có đầy đủ chức năng và sẵn sàng sử dụng chỉ bằng ba thao tác đơn giản:
Sau đó, bạn nhấn nút “ Tạo ứng dụng ” và xem điều kỳ diệu tự diễn ra. Vì vậy, mặc dù quá trình tạo Ứng dụng trò chuyện React khá đơn giản, nhưng chúng tôi thực sự khuyên bạn nên tạo ứng dụng trò chuyện cho dự án tiếp theo của mình bằng cách sử dụng Trình tạo ứng dụng web Full Stack để tạo một ứng dụng hiệu quả trong nháy mắt.
Mọi câu chuyện tuyệt vời đều bắt đầu bằng một tiêu đề và mọi ứng dụng React tuyệt vời đều bắt đầu bằng một cái tên. Bắt đầu quá trình tạo Ứng dụng React Chat nhanh chóng và dễ dàng bằng cách chọn tên cho dự án.
Trong bước này, bạn đặt cùng một bộ khung cho ứng dụng của mình một cách ẩn dụ bằng cách chọn ngăn xếp của nó, bao gồm cả mặt trước, mặt sau và cơ sở dữ liệu của câu hỏi.
Sau khi khung xương của bạn được ghép lại với nhau một cách ẩn dụ, bạn đã sẵn sàng để thêm lớp da đẹp cho nó, bằng cách chọn một thiết kế tuyệt đẹp từ một số biến thể làm sẵn và sẵn sàng sử dụng.
Trong bước này, để tiếp tục tương tự từ các bước trước, hãy đặt một số cơ nghiêm trọng lên skelly. Và ý của chúng tôi là tạo lược đồ cơ sở dữ liệu cho Ứng dụng trò chuyện React của bạn. Và nếu bạn không muốn tự mình làm điều đó, nền tảng của Flatlogic có lược đồ sẵn sàng sử dụng cho các ứng dụng Trò chuyện. Bây giờ chọn cơ sở dữ liệu bạn cần từ danh sách. Điều tuyệt vời nữa ở đây là khả năng mày mò với các lược đồ làm sẵn, để chúng phù hợp hơn với nhu cầu của bạn.
Những gì bạn cần làm bây giờ chỉ đơn giản là xem lại các lựa chọn của bạn cho ứng dụng và nhấn nút “Tạo dự án”, để Full Stack Web App Builder của Flatlogic sẽ phát huy tác dụng kỳ diệu của nó. Sau một vài phút ngắn ngủi, bạn sẽ có trong tay ứng dụng trò chuyện React hoạt động hoàn chỉnh.
Trong phần này của bài viết, chúng tôi muốn chia sẻ với bạn 5 ví dụ về Ứng dụng trò chuyện React mà chúng tôi thấy được thực hiện khá tốt và giải thích lý do tại sao chúng tôi nghĩ như vậy.
Ví dụ №1 – Cửa sổ trò chuyện đơn giản được xây dựng trong React bởi Joshua P. Larson
Chúng tôi coi Ứng dụng trò chuyện React này được tạo ra tốt vì nó cho thấy rằng không nhất thiết phải có thật nhiều tính năng hào nhoáng mới được coi là một bổ sung tốt, đáng tin cậy cho dự án của bạn. Chậm và ổn định, hoặc thích hợp hơn với tình huống hiện tại, tốt đẹp và đơn giản, sẽ giành chiến thắng trong cuộc đua.
Nguồn – codespots.com/library/item/3749
Ví dụ №2 – Ứng dụng trò chuyện của DanLowo
Ứng dụng này là một Ứng dụng React được thiết kế đẹp mắt và có nhiều kiểu dáng, phần nào gợi nhớ đến một Tin nhắn trực tiếp trên Instagram được làm tốt hơn. Chúng tôi đưa nó vào danh sách các ví dụ của mình như một cách để truyền đạt tầm quan trọng của việc làm cho ứng dụng trò chuyện của bạn hấp dẫn trực quan đối với người dùng cuối. Cũng cần đề cập rằng Trình tạo ứng dụng web Full Stack của Flatlogic cho phép bạn chọn thiết kế của ứng dụng bạn tạo từ danh sách các biến thể bắt mắt.
Nguồn – github.com/DanLowo/Chat-Application
Ví dụ №3 – Một ứng dụng trò chuyện dựa trên React sử dụng chatengine.io Rest API
Ứng dụng Trò chuyện React có trong danh sách các tính năng như tạo nhóm và đăng nhập Tài khoản Google. Ứng dụng cụ thể này cũng phục vụ một mục đích khá cao cả – mang đến cho mọi người một nền tảng để chia sẻ những lo lắng và suy nghĩ của họ với bất kỳ ai sẵn sàng lắng nghe trên cơ sở ẩn danh. Vì vậy, để có một mục tiêu thuần túy và cho các tính năng sát thủ trong danh sách ví dụ của chúng tôi, nó đi!
Nguồn – Reacjsexample.com/a-react-based-chat-app-using-chatengine-io-rest-api-and-has-features-of-creating-groups/
Ví dụ №4 – EfeChat của Alper Efe Şahin
Chúng tôi cảm thấy cần phải thêm ví dụ này vào danh sách của mình như một cách truyền tải thông điệp về sự đơn giản. Chủ yếu là sự đơn giản trong cách sử dụng mà người dùng cuối nên có khi sử dụng Ứng dụng trò chuyện React của bạn. Và EfeChat dễ dàng giải quyết vấn đề này vì các tính năng của nó khá đơn giản và trực quan – những tính năng mà người dùng có thể không nhận thấy. Nhưng hãy tin chúng tôi, việc thiếu hai tính năng này sẽ dễ thấy nhất đối với người dùng.
Nguồn -github.com/alper-efe-sahin/EfeChat-Reactjs
Ví dụ №5 – trò chuyện dễ thương của Asif Azad
Và chúng tôi muốn kết thúc danh sách của mình bằng trò chuyện dễ thương – một trò chuyện đơn giản nhưng đầy phong cách theo đúng nghĩa của nó, đưa chúng ta trở lại những cuộc trò chuyện của những năm 2000 như ICQ với thiết kế tổng thể của nó. Nhưng đó không phải là ý chính đằng sau việc đưa nó vào danh sách này. Đó sẽ là điều cần thiết để làm cho Ứng dụng trò chuyện React của bạn tương thích với điện thoại thông minh, giống như trò chuyện dễ thương, vì hầu hết lưu lượng truy cập internet ngày nay đến từ điện thoại thông minh, thay vì máy tính.
Nguồn – bestoreactjs.com/repo/BRAINIAC2677-cute-chat-react-react-apps
Bây giờ chúng ta hãy nhắc lại một vài điểm quan trọng:
Và đó là tất cả cho ngày hôm nay. Chúng tôi hy vọng rằng bạn sẽ thấy bài viết này thực sự hữu ích và hữu ích. Vì vậy, chúc một ngày tốt lành và như mọi khi, hãy đọc thêm các bài viết của chúng tôi.
Bài viết gốc có nguồn gốc tại: https://flatlogic.com
#socket #react-native #react
1674388440
A real time chat application in Vue, Socket.IO, MongoDB.
Client: install dependencies and run client on port 8080
cd client
npm install
npm run serve
Server: install dependencies and run server on port 1337
cd server
npm install
npm run dev
Client:
Server:
Author: ConstantinoBernardo
Source code: https://github.com/ConstantinoBernardo/vue-socketio-chat
License: MIT license
1672322640
amphp/socket
is a socket library for establishing and encrypting non-blocking sockets PHP based on Amp.
This package can be installed as a Composer dependency.
composer require amphp/socket
Documentation can be found on amphp.org as well as in the ./docs
directory.
You can find more examples in the ./examples
directory.
<?php // basic (and dumb) HTTP client
require __DIR__ . '/../vendor/autoload.php';
// This is a very simple HTTP client that just prints the response without parsing.
// league/uri-schemes required for this example.
use Amp\ByteStream;
use Amp\Loop;
use Amp\Socket\ClientTlsContext;
use Amp\Socket\ConnectContext;
use Amp\Socket\EncryptableSocket;
use League\Uri;
use function Amp\Socket\connect;
Loop::run(static function () use ($argv) {
$stdout = ByteStream\getStdout();
if (\count($argv) !== 2) {
yield $stdout->write('Usage: examples/simple-http-client.php <url>' . PHP_EOL);
exit(1);
}
$uri = Uri\Http::createFromString($argv[1]);
$host = $uri->getHost();
$port = $uri->getPort() ?? ($uri->getScheme() === 'https' ? 443 : 80);
$path = $uri->getPath() ?: '/';
$connectContext = (new ConnectContext)
->withTlsContext(new ClientTlsContext($host));
/** @var EncryptableSocket $socket */
$socket = yield connect($host . ':' . $port, $connectContext);
if ($uri->getScheme() === 'https') {
yield $socket->setupTls();
}
yield $socket->write("GET {$path} HTTP/1.1\r\nHost: $host\r\nConnection: close\r\n\r\n");
while (null !== $chunk = yield $socket->read()) {
yield $stdout->write($chunk);
}
// If the promise returned from `read()` resolves to `null`, the socket closed and we're done.
// In this case you can also use `yield Amp\ByteStream\pipe($socket, $stdout)` instead,
// but we want to demonstrate the `read()` method here.
});
<?php // basic (and dumb) HTTP server
require __DIR__ . '/../vendor/autoload.php';
// This is a very simple HTTP server that just prints a message to each client that connects.
// It doesn't check whether the client sent an HTTP request.
// You might notice that your browser opens several connections instead of just one,
// even when only making one request.
use Amp\Loop;
use Amp\Socket\ResourceSocket;
use Amp\Socket\Server;
use function Amp\asyncCoroutine;
Loop::run(static function () {
$clientHandler = asyncCoroutine(static function (ResourceSocket $socket) {
$address = $socket->getRemoteAddress();
$ip = $address->getHost();
$port = $address->getPort();
echo "Accepted connection from {$address}." . PHP_EOL;
$body = "Hey, your IP is {$ip} and your local port used is {$port}.";
$bodyLength = \strlen($body);
$req = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: {$bodyLength}\r\n\r\n{$body}";
yield $socket->end($req);
});
$server = Server::listen('127.0.0.1:0');
echo 'Listening for new connections on ' . $server->getAddress() . ' ...' . PHP_EOL;
echo 'Open your browser and visit http://' . $server->getAddress() . '/' . PHP_EOL;
while ($socket = yield $server->accept()) {
$clientHandler($socket);
}
});
If you discover any security related issues, please email me@kelunik.com
instead of using the issue tracker.
Author: Amphp
Source Code: https://github.com/amphp/socket
License: MIT license
1667353680
SwiftSocket library provides as easy to use interface for socket based connections on server or client side. Supports both TCP and UDP sockets.
Installation
Add this to your Podfile
:
pod 'SwiftSocket'
And run then pod install
github "swiftsocket/SwiftSocket"
Code examples
// Create a socket connect to www.apple.com and port at 80
let client = TCPClient(address: "www.apple.com", port: 80)
You can also set timeout to -1
or leave parameters empty (client.connect()
) to turn off connection timeout.
switch client.connect(timeout: 10) {
case .success:
// Connection successful 🎉
case .failure(let error):
// 💩
}
let data: Data = // ... Bytes you want to send
let result = client.send(data: data)
var data = client.read(1024*10) //return optional [Int8]
client.close()
let client = TCPClient(address: "www.apple.com", port: 80)
switch client.connect(timeout: 1) {
case .success:
switch client.send(string: "GET / HTTP/1.0\n\n" ) {
case .success:
guard let data = client.read(1024*10) else { return }
if let response = String(bytes: data, encoding: .utf8) {
print(response)
}
case .failure(let error):
print(error)
}
case .failure(let error):
print(error)
}
func echoService(client: TCPClient) {
print("Newclient from:\(client.address)[\(client.port)]")
var d = client.read(1024*10)
client.send(data: d!)
client.close()
}
func testServer() {
let server = TCPServer(address: "127.0.0.1", port: 8080)
switch server.listen() {
case .success:
while true {
if var client = server.accept() {
echoService(client: client)
} else {
print("accept error")
}
}
case .failure(let error):
print(error)
}
}
Author: Swiftsocket
Source Code: https://github.com/swiftsocket/SwiftSocket
License: BSD-3-Clause license
1666279618
Build a responsive cross-platform Google Docs Clone using Flutter & Node.js. This tutorial is designed for beginners in Node.js and no prior knowledge Javascript is required. This course will go through Google Authentication WITHOUT Firebase, keeping the users logged in, creating new documents, viewing the list of documents created by user, updating the title of the document, sharing link of the document, adding a rich text editor, collaboratively editing with as many users as you want and creating responsive design. We will be using Flutter, Node, Express, Socket, MongoDB and Riverpod.
Prerequisites: Flutter & Dart Basics
Flutter Version: 3.3
⭐️ Contents ⭐️
⌨️ (0:00:00) Intro
⌨️ (0:00:57) Creating Flutter Project
⌨️ (0:02:56) Designing Login Screen
⌨️ (0:09:24) Google Cloud Platform oAuth Client ID
⌨️ (0:13:00) Google Auth Android Setup
⌨️ (0:15:30) Google Auth iOS Setup
⌨️ (0:17:25) Google Auth Web Setup
⌨️ (0:19:17) Important Note on Auth
⌨️ (0:20:39) Running on Web on specific port
⌨️ (0:21:19) Google Sign In using Node.js
⌨️ (0:32:45) What is Node.js?
⌨️ (0:35:53) Creating & setting up Node Server
⌨️ (0:54:00) MongoDB Setup
⌨️ (1:01:01) Creating Signup API
⌨️ (1:32:16) Calling Signup API - Client Side
⌨️ (2:00:04) Persisting the State - Explanation
⌨️ (2:03:52) Generating JWT
⌨️ (2:07:31) Auth Middleware
⌨️ (2:22:50) Local Storage
⌨️ (2:41:15) Testing on Android
⌨️ (2:42:23) Routing
⌨️ (2:51:28) Creating NavBar
⌨️ (2:53:44) Signing Out
⌨️ (2:59:52) Creating New Document
⌨️ (3:23:32) Displaying all documents created by Me
⌨️ (3:37:57) Designing Document Screen
⌨️ (3:55:39) Updating Document Title
⌨️ (4:10:20) Socket Introduction & Connection
⌨️ (4:29:23) Collaborative Editing
⌨️ (4:49:26) Auto-Save
⌨️ (4:58:01) Routing Back to Main Page
⌨️ (4:59:45) Sharing Link
⌨️ (5:01:42) Conclusion
Resources:
SHA-1 Key: https://stackoverflow.com/questions/15727912/sha-1-fingerprint-of-keystore-certificate
Node Website: http://nodejs.org
NPM Website: https://www.npmjs.com
MongoDB: http://mongodb.com/
More about Status Codes: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
💻 Source Code: https://github.com/RivaanRanawat/flutter-google-docs-clone
#flutter #node #expressjs #socket #mongodb #riverpod
1665644390
In this tutorial, you'll learn how to create a Chat App from scratch with Node.js, React.js and Socket.io The App will be a web chat app made in React with sockets, communicating with the server and sending information back and forth, live.
The code on github: https://github.com/turcuciprian/0001_cwc_chat_app-simple-react_and_nodejs
Subscribe: https://www.youtube.com/channel/UC4u0FXRaTDwc-SKUTGto2Kg/featured
#chatapp #node #react #socket
1664338680
🌟 Connect easily to a spacebro server.
yarn add spacebro-client
# or
npm i -S spacebro-client
First, you need to start a spacebro server.
$ npm i -g spacebro # or yarn global add spacebro
$ spacebro
Then, write the following client code:
const { SpacebroClient } = require('spacebro-client')
const client = new SpacebroClient({
host: '127.0.0.1',
port: 36000,
channelName: 'bar',
client: {
name: 'foo',
description: "a foo tool",
in: {
inFoo: {
eventName: "inFoo",
description: "Input foo",
type: "all"
}
},
out: {
outBar: {
eventName: "outBar",
description: "Output bar",
type: "all"
}
}
},
connection: "bar/outBar => bar/inFoo"
})
client.on('inFoo', (data) => console.log('inFoo', data))
client.emit('outBar', { do: stuff})
The connection string was sent to the spacebro server, that will then connects every event named outBar
from client bar
to a new event named inFoo
sent to client bar
class SpacebroClient([options], [connect])
Look for a server, and return a handle to the connection.
// For more details about possible options, see below.
const client = new SpacebroClient({
host: '127.0.0.1',
port: 8888,
client: {name: 'foo'},
channelName: 'bar'
})
name | default | required | description |
---|---|---|---|
host | - | required | The spacebro server's address. Ignored if connect is false. |
port | - | required | The spacebro server's address. Ignored if connect is false. |
client.name | null | recommended | Your client's name. Can be useful to perform targeted events and for monitoring. |
channelName | null | recommended | The channel your app will communicate in. This is especially usefull if you have multiple apps using the same server. |
verbose | true | optional | Should spacebro-client display logs (connection / emission / reception)? |
sendBack | true | optional | Should this client receive the events it sent? |
If the connect
parameter is false, then the options are saved and a disconnected handle is returned; you have to call its connect
method later before you can emit or receive events.
Default value: true
const client = new SpacebroClient({
client: {name: 'myClient'},
channelName: 'someChannel'
}, false)
// ...
client.connect('127.0.0.1', 8888)
create([options])
Look for a server, and creates a handle to the connection. Takes the same options as new SpacebroClient
. Returns a Promise like client.connect
.
setDefaultSettings(options, [verbose])
Overwrite the default options of new SpacebroClient
with the given options.
If standard-settings is installed in your module, spacebro-client
will call this function with the contents of services.spacebro
from your settings file.
client.connect(address, port)
Look for a server, and connect client
to this server. Returns a Promise that resolves to client
when the connection is established, or throws an error if the connection fails.
client.emit(eventName[, data])
Broadcast a specific event to all the clients in the channel. data
must be a JSON object.
client.sendTo(eventName, target[, data])
Send an event to a specific target in the channel. data
must be a JSON object.
client.on(eventName, handler)
Listen to a specific event.
client.once(eventName, handler)
Listen to a specific event only once.
client.off(eventName)
Remove a specific event listener.
client.disconnect()
Close the connection.
Spacebro now works with acknowlegdments too !
const { SpacebroClient } = require('spacebro-client')
const client = new SpacebroClient({
host: '127.0.0.1',
port: 36000,
channelName: 'bar',
client: {
name: 'foo',
description: "a foo tool",
in: {
inFoo: {
eventName: "inFoo",
description: "Input foo",
type: "all"
}
},
out: {
outBar: {
eventName: "outBar",
description: "Output bar",
type: "all"
}
}
},
connection: "bar/outBar => bar/inFoo"
})
client.on('inFoo', (data, fn) => {
console.log('inFoo', data)
fn('thank you')
})
client.emit('outBar', { do: stuff}, function (data) {
console.log('Received from callback: ' + data)
})
You can use spacebro-client in the browser. You will need the following dependencies:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.0/socket.io.js"></script>
<script src="https://wzrd.in/standalone/socketio-wildcard@latest"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-signals/1.0.0/js-signals.min.js"></script>
After adding these dependencies, you can include the spacebro-client lib like any script:
<script src="./dist/spacebro-client.js"></script>
Then use the window.spacebroClient
object.
Spacebro-client also works in Electron. You just require('spacebro-client')
in your electron main process and use ipc or web-contents to forward events to the renderer process.
From the example/electron/
folder of this repository:
// In the main process.
const { app, BrowserWindow } = require('electron')
const { SpacebroClient } = require('../../dist/spacebro-client')
let win = null
const client = new SpacebroClient({
host: '127.0.0.1',
port: 8888,
client: {name: 'foo'},
channelName: 'bar'
})
app.on('ready', () => {
win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL(`file://${__dirname}/index.html`)
for (const eventName of ['hello', 'world']) {
client.on(eventName, (data) => {
win.webContents.send(eventName, data)
})
}
win.webContents.on('did-finish-load', () => {
setTimeout(() => { client.emit('hello', { hello: 'world' }) }, 3000)
setTimeout(() => { client.emit('world', { world: 'hello' }) }, 5000)
})
})
<!-- index.html -->
<html>
<body>
<script>
require('electron').ipcRenderer.on('hello', (event, message) => {
console.log(message)
})
require('electron').ipcRenderer.on('world', (event, message) => {
console.log(message)
})
</script>
</body>
</html>
You can find many real life examples in the example/
folder of this repository.
newClient
event 👋The Spacebro server automatically broadcasts a newClient
event when a client connects. Thus, you should avoid using that event name. See the example/simple-node
script for more details.
If you want to use spacebro-client
in an Electron app, you'll have to use electron-rebuild in order to rebuild MDNS according to the version of Node.js embedded with Electron.
Use the following commands:
$ npm i --save-dev electron-rebuild # or yarn
$ ./node_modules/.bin/electron-rebuild # call the executable every time you add a new native module
You can also add "rebuild": "./node_modules/.bin/electron-rebuild"
to your package.json
and run npm run rebuild
for convenience.
You need to use at least yarn version 0.17.8
. You might have similar problems with outdated versions of npm, simply try to update it.
If the spacebro server is on https, use following settings:
'service': {
'spacebro': {
'host': 'https://example.com'
'port': 0
}
}
If the server url is something like https://example.com/subdir
. You can use this url as host. Spacebro will process subdir
as a path, contrary to socket.io that would process subdir
as a namespace.
That means the requested urls will look like https://example.com/subdir/?EIO=3&transport=polling&sid=<id>
Do not try to test with 'ping'
and 'pong'
events, those are reserved.
- `ping`. Fired when a ping packet is written out to the server.
- `pong`. Fired when a pong is received from the server.
Please follow Standard JS conventions.
The package has lint testing and unit testing baked-in. Please use npm run test
to run both sets of tests before making a pull request. Use npm run build
to transpile the project.
The project's release versions are named after stars in Andromeda . The current version is named Sirrah.
Enjoy !
Author: Spacebro
Source Code: https://github.com/spacebro/spacebro-client
License: MIT license
1664334720
🚀 Spacebro 💫
In reference to Spacebrew by Rockwell Lab (http://www.rockwellgroup.com/search/LAB)
Spacebro uses:
Install it globally
$ npm i -g spacebro
# or
$ yarn global add spacebro
And just run the bin
:
$ spacebro
You can configure it via CLI args:
$ spacebro --server.port 8888
# to view all possible arguments
$ spacebro --help
NOTE: Spacebro uses standard-settings, see the doc there to change settings via argv, env or file
$ npm i --save spacebro
# or
$ yarn add spacebro
And then connection with a spacebro-client
as is. The spacebro client allows to connect your node application to spacebro server, just by requiring it.
See spacebro-client to learn more.
For openFramework you can also use ofxSpaceBro.
For python you can also use pySpacebroClient.
flag | what it does |
---|---|
-h, --help | output usage information |
-V, --version | output the version number |
-P, --server.port <n> | give a port to spacebro |
-M, --mute | option to hide informations |
--semiverbose | do not show events datas in logs |
-H, --hidedashboard | Allow to hide dashboard |
Once connected, you can interact with spacebro, to know which other client is connected, what are the connections between them, add your own connections, ...
A connection
is a link between an output of a client and an input of an other client. It is explained in details below.
register
Mandatory event for a client to send to spacebro, this is implemented inside spacebro-client
so you should not have to use this, unless you are writing a client plugin in an other language.
The data sent with the register
event should include the keys below:
{
channelName: 'media-stream', // the socket.io channel to connect to
client: {
name: 'myclientname',
description: 'Describe here what your client does',
in: {// input events your client will react to
inMedia: {
eventName: "inMedia",
description: "Describe the input event here",
type: "all" // use all by default, or mention a type of data
expected
},
otherInput: {
...
}
},
out: { // output events your client will send
outMedia: {
eventName: "outMedia",
description: "Describe the input event here",
type: "all" // use all by default, or mention a type of data
}
}
}
}
addConnections
Add a connection between an output of a client and the input of an other client.
The data can be a connection or an array of connections with a connection respecting this schema
{
src: {
clientName: 'myclient',
eventName: 'outMedia'
},
tgt: {
clientName: 'myotherclient',
eventName: 'inMedia'
}
}
or a string or array of strings with this syntax:
myclient/outMedia => myotheclient/inMedia
When myclient
emits a outMedia
event, it will be forwarded to myotherclient
with the event name inMedia
A connection
event is emitted to all clients with the updated
removeConnections
Removes all connections listed in the data of this event: an array or single connection, in the schema seen above.
A connection
event is emitted to all clients with the updated connections list
replaceConnections
Removes all connections on the current channel, and add the connections listed in the data of this event.
A connection
event is emitted to all clients with the updated connections list
getConnections
Ask for a connection
event, which is emitted to all clients with the current connection list on the current channel.
getClients
Ask for a clients
event, which is emitted to all clients with the current client list on the current channel.
saveGraph
Save the current state: list of clients and list of connections, into the settings file mentioned when running spacebro
For example, run
spacebro --settings /path/to/my-settings-file.json
Connect some clients, add some connections, send a saveGraph
event, and the state of the graph will be saved in this settings file.
newClient
spacebro broadcasts a newClient
event when a new connection is created, with the client name as client.name
property value. Typically, you'd do on the client side:
spacebroClient.on('newClient', (data) => {
console.log(`${data.client.name} has joined.`)
})
clients
spacebro broadcasts a clients
event after a client registered or after receiving a getClients
event.
data is an array of clients.
connections
spacebro broadcasts a connections
event after a new connection is added or after receiving a getConnections
event.
data is an array of connections in the schema descibed below:
{
src: {
clientName: 'myclient',
eventName: 'outMedia'
},
tgt: {
clientName: 'myiotherclient',
eventName: 'inMedia'
}
}
Do not try to test with 'ping'
and 'pong'
events, those are reserved.
- `ping`. Fired when a ping packet is written out to the server.
- `pong`. Fired when a pong is received from the server.
npm run test
You can develop on spacebro, by running:
yarn dev
you can build with yarn build
We use galaxies names for our release name, listed here here. We are currently at Black Eye.
You can check the examples/
folder, as well as the spacebro-client examples for real life examples.
Please follow standard style conventions.
Author: Spacebro
Source Code: https://github.com/spacebro/spacebro