flutter 聊天应用_如何构建自己的实时聊天应用

flutter 聊天应用

by Sudheesh Shetty

由Sudheesh Shetty

如何构建自己的实时聊天应用 (How to build your own real-time chat app)

Messaging apps are surging in popularity. The past few years have brought apps like WhatsApp, Telegram, Signal, and Line.

通讯应用程序越来越受欢迎。 在过去的几年中,出现了诸如WhatsApp,Telegram,Signal和Line之类的应用程序。

People seem to prefer chat-based applications because they allow for real-time interaction. They also add a personal touch to the experience.

人们似乎更喜欢基于聊天的应用程序,因为它们允许实时交互。 他们还为体验增添了个性。

I recently attended a workshop conducted by the Free Software Movement Karnataka in Bangalore where I mentored a group of college students.

我最近在班加罗尔参加了由卡纳塔克邦自由软件运动举办的研讨会,在那里我指导了一群大学生。

During the interactions, I observed certain things:

在交互过程中,我观察到某些事情:

  1. Despite encouraging students to interact with the mentor, communication was always one-sided.

    尽管鼓励学生与导师互动,但交流总是单方面的。
  2. Students often felt too shy to ask questions during the sessions.

    在课程中,学生常常感到害羞而无法提问。
  3. They were more comfortable asking questions and getting feedback in one-on-one conversations.

    他们更愿意在一对一对话中提出问题并获得反馈。

So we had to find a solution to break the ice between mentors and students. A local chat application came handy in this situation. People love to be anonymous, which gives them more power to express themselves and ask anytime anywhere. This is the same mantra used by most of the popular forums on the internet, such as Reddit and 4chan. These are just a few giant examples of semi-anonymous apps.

因此,我们必须找到一种解决方案,以打破导师与学生之间的僵局。 在这种情况下,可以使用本地聊天应用程序。 人们喜欢匿名,这使他们有更多的能力表达自己的意见并随时随地提问。 这与Internet上大多数流行论坛(如Reddit和4chan)所使用的口头禅相同。 这些只是半匿名应用程序的一些大型示例。

So I started thinking about this idea. I came up with some of the basic requirements and features.

所以我开始考虑这个想法。 我提出了一些基本要求和功能。

  1. Users register by giving a handle, which is unique to every user (a dummy name). Only the handle will be revealed to other users. So people are free to choose any handle and hence they stay anonymous.

    用户通过提供一个句柄进行注册,该句柄对每个用户都是唯一的(虚拟名称)。 只有句柄将向其他用户显示。 因此人们可以自由选择任何句柄,因此他们保持匿名。
  2. A member can see other members who are online. They have an option to go public, which broadcast the message to all online members in the chat.

    成员可以查看其他在线成员。 他们可以选择公开,然后将消息广播到聊天中的所有在线成员。
  3. For private messages, the sender should first send a request to the other member. Other members upon accepting the request can have private chat with them.

    对于私人消息,发件人应首先向其他成员发送请求。 其他成员在接受请求后可以与他们进行私人聊天。

技术,使用的工具 (Technology, Tools used)

  1. MEAN Stack(Mongo, Express, Angular, Node).

    MEAN Stack(Mongo,Express,Angular,Node)。
  2. Sockets to enable one-on-one communication in real time

    用于实时进行一对一通讯的套接字
  3. AJAX for sign-up and login

    AJAX进行注册和登录

那么,如何创建一个简单的聊天应用程序? (So how do you create a simple chat application?)

In this tutorial, I’m going to help you create your own chat application. You can later integrate as a widget into any project! This tutorial won’t concentrate on the complete development of a chat application. But it will help you build one.

在本教程中,我将帮助您创建自己的聊天应用程序。 您以后可以将其作为小部件集成到任何项目中! 本教程将不会专注于聊天应用程序的完整开发。 但这将帮助您建立一个。

Pre-requisite : You need to know some basic knowledge of MEAN Stack, as we are making use of it to build one.

先决条件:您需要了解MEAN Stack的一些基本知识,因为我们正在利用它来构建MEAN Stack。

First, create a directory structure something like this.

首先,创建类似这样的目录结构。

Install Node.js and MongoDB.

安装Node.jsMongoDB

We’ll be making use of AngularJS 1 for this tutorial. Download the AngularJS library from here and copy it to the lib folder in Client directory.

在本教程中,我们将使用AngularJS 1。 从此处下载AngularJS库,并将其复制到Client目录中的lib文件夹。

If you like to beautify the application you can download any CSS libraries and copy them to lib as well.

如果您想美化该应用程序,则可以下载任何CSS库并将它们也复制到lib中。

构建服务器 (Building the Server)

Step 1 — Start the project :

步骤1 —启动项目:

Go to Server directory and run this command:

转到服务器目录并运行以下命令:

npm init

This will start a new project. Provide all the details required. The package.json will be created and will look something like this.

这将启动一个新项目。 提供所需的所有详细信息。 package.json将被创建,看起来像这样。

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

Step 2 — Install the dependencies.

第2步 -安装依赖项。

  • socket.io — is a javascript library for real-time web applications. It enables real-time, bi-directional communication between web clients and servers.

    socket.io —是用于实时Web应用程序的JavaScript库。 它支持Web客户端和服务器之间的实时双向通信。

  • express — is a Node.js web application framework. It provides the set of features to develop the web and mobile applications. One can respond to HTTP request using different middlewares and also render HTML pages.

    express —是一个Node.js Web应用程序框架。 它提供了开发Web和移动应用程序的功能集。 人们可以使用不同的中间件来响应HTTP请求,还可以呈现HTML页面。

npm install --save socket.ionpm install --save express

This will install required dependencies and add those to package.json. An extra field will be added to package.json which will look like this:

这将安装所需的依赖项并将其添加到package.json中。 一个额外的字段将添加到package.json中 ,如下所示:

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

Step 3 — Creating the Server

第3步-创建服务器

Create a server which serves at port 3000 and will send the html when called.

创建一个服务器,该服务器的端口为3000,并在调用时发送html。

Initialize a new socket connection by passing HTTP object.

通过传递HTTP对象来初始化新的套接字连接。

Event connection will be listening for incoming sockets.

事件连接将监听传入的套接字。

Each socket emits disconnect event which will be called whenever a client disconnects.

每个套接字都发出断开连接事件,只要客户端断开连接,该事件就会被调用。

  • socket.on waits for the event. Whenever that event is triggered the callback function is called.

    socket.on等待事件。 每当触发该事件时,都会调用回调函数。

  • io.emit is used to emit the message to all sockets connected to it.

    io.emit用于将消息发送到与其连接的所有套接字。

The syntax is:

语法为:

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

Create a server with name server.js. It should:

创建一个名称为server.js的服务器 这应该:

  • print a message to the console upon a user connecting

    用户连接后将消息打印到控制台
  • listen for chat message events and broadcast the received message to all sockets connected.

    侦听聊天消息事件,并将接收到的消息广播到所有连接的套接字。

  • Whenever a user disconnects, it should print the message to the console.

    每当用户断开连接时,都应将消息打印到控制台。

The server will look something like this:

服务器将如下所示:

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

建立客户 (Building the Client)

Create the index.html in the client directory, style.css in the css directory and app.js in js directory in the client.

在客户端目录中创建index.html,在css目录中创建style.css,在js目录中创建app.js。

index.html:

index.html:

Let us write a simple HTML which can take our message and also display it.

让我们编写一个简单HTML,它可以接收我们的消息并显示它。

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

在HTML脚本中包含socket.io-clientangular.js

<script src="/path/to/angular.js"></script><script src="/socket.io/socket.io.js"></script>

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

socket.io为我们服务于客户。 默认情况下,它连接到为该页面提供服务的主机。 最终HTML看起来像这样:

<!doctype html><html ng-app="myApp">  <head>    <title>Socket.IO chat</title>    <link rel="stylesheet" href="/css/style.css">    <script src="/lib/angular/angular.js"></script>    <script src="/socket.io/socket.io.js"></script&gt;    <script src="http://code.jquery.com/jquery-1.11.1.js">    </script>    <script src="/js/app.js"></script>  </head>  <body ng-controller="mainController">    <ul id="messages"></ul>    <div>      <input id="m" ng-model="message" autocomplete="off" />      <button ng-click="send()">Send</button>    </div>  </body></html>

css/style.css:

css / style.css:

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

给它一些样式,使其看起来像一个聊天框。 您可以使用任何库。

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

js/app.js:

js / app.js:

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

创建一个angular.js应用并初始化套接字连接。

  • socket.on listens for a particular event. It calls a callback function whenever that event is called.

    socket.on侦听特定事件。 每当调用该事件时,它将调用一个回调函数。

  • socket.emit is used to emit the message to the particular event.

    socket.emit用于将消息发送到特定事件。

Basic syntax of both are:

两者的基本语法是:

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

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

因此,每当键入消息并单击按钮时,就调用函数以发送消息。

Whenever the socket receives a message, display it.

每当套接字收到一条消息时,就显示它。

The JavaScript will look something like this:

JavaScript将如下所示:

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

运行应用程序 (Running the application)

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

转到服务器所在的服务器目录。 使用以下命令运行服务器:

node server.js

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

服务器开始在端口3000上运行。请转到浏览器并键入以下URL:

http://localhost:3000

如何改善相同的应用 (How to improve the same application)

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

您可以设计一个数据库来保存用户详细信息和消息。 如果设计具有可伸缩性,那将是很好的,这样您以后可以添加更多功能。

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

您需要安装Mongoose或MongoDB模块才能使用Mongo数据库:

npm install --save mongoose

or:

要么:

npm install --save mongodb

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

这是使用mongoosemongodb模块的文档。

Here’s what my schema design looks like:

这是我的架构设计的样子:

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

Here, the status of each member can be:

在这里,每个成员的状态可以是:

  • Friend: Stating that the member is a friend.

    朋友:说明成员是朋友。
  • Pending: If the member has not yet accepted.

    待审核:如果该会员尚未接受。
  • Blocked: If the member has blocked the other member.

    被阻止:如果该成员已阻止另一个成员。

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

假设成员拒绝了聊天请求。 然后,发件人可以再次发送聊天请求。 用户还可以通过创建额外的集合来保存消息。 每个文档将具有消息,发送者,接收者和时间。

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

因此,请根据您的特定需求以及您希望如何处理消息来设计数据库。

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

2.创建REST API以服务于客户端。 例如,端点发送一个主页,用户可以从该主页发出其他请求。

Few of my API endpoints are:

我的API端点很少是:

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

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

3.考虑一些很酷的附加功能并实施它们。

I have created a chat application of my own:

我创建了自己的聊天应用程序:

sudheeshshetty/ChatContribute to Chat development by creating an account on GitHub.github.com

sudheeshshetty / Chat 通过在GitHub上创建一个帐户来促进聊天开发。 github.com

Here’s a quick glance at my chat application:

快速浏览一下我的聊天应用程序:

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

请仔细看一下,如果喜欢,请在右上角加星号。 有很多方法可以改善此应用程序。 如果您有任何建议,请发送至sudheeshshetty@gmail.com。

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

如果您发现这有帮助,可以点击此处,单击绿色的心,这样可以让更多的人看到。 您也可以在GitHubTwitter 上关注我

翻译自: https://www.freecodecamp.org/news/building-a-chat-application-with-mean-stack-637254d1136d/

flutter 聊天应用

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值