用 Flutter、Socket.io 和 Node.js 构建一对一实时聊天 app(上)

我写过很多关于实时应用的文章,主要讨论的是如何使用 socket.io,以及如何构建简单的一对多线上聊天 app(点击此处阅读),本文会教大家构建一对一线上聊天 app。


你能学会:

  • 使用 socket.io 在两个设备之间创建实时连接;
  • 理解 room 的概念,如何用 socket.io 使用 room;
  • 一些局部作用域模型库知识。


前期准备

在 PC 端安装并运行:

Room

Room 是逻辑分组机制,只能用于特定的 socket。

我们通过一个简单的图形来认识它:

以前,用户发送一条消息,服务器会把该消息发送给该用户之外的所有用户。

使用 room 之前

使用 room 之后,服务器只把消息发送给指定用户。

使用 room 之后


这样我们就可以使用 room 进行一对一聊天了,我们开始吧。


Node.js(服务器端)

创建一个新的 node 项目,并安装以下依赖:

找到 package.json,添加 dev 脚本:

1_EMbJnRl2LPlIE8NV0W104Q

package.json 中的 dev 脚本

然后,在 index.js 文件中添加以下代码:

const app = require('express')()
const http = require('http').createServer(app)
const io = require('socket.io')(http);

app.get('/', (req, res) => {
    res.send("Node Server is running. Yay!!")
})

io.on('connection', socket => {
    //Get the chatID of the user and join in a room of the same chatID
    chatID = socket.handshake.query.chatID
    socket.join(chatID)

    //Leave the room if the user closes the socket
    socket.on('disconnect', () => {
        socket.leave(chatID)
    })

    //Send message to only a particular user
    socket.on('send_message', message => {
        receiverChatID = message.receiverChatID
        senderChatID = message.senderChatID
        content = message.content

        //Send message to only that particular room
        socket.in(receiverChatID).emit('receive_message', {
            'content': content,
            'senderChatID': senderChatID,
            'receiverChatID':receiverChatID,
        })
    })
});

http.listen(process.env.PORT)

连接到我们服务器的每个用户都有一个特定的 chatID,这个 ID 就是他们加入房间时的 ID。所以如果有人想对某个指定用户发送消息,首先需要知道对方的 ID。

现在,服务器端的代码已经完成,接下来我们将其部署到 Heroku。

在名为 Procfile 的根目录下创建一个新文件,添加以下行:

web: node index.js

再创建一个名为 .gitignore 的文件,添加以下行:

/node_modules

之后,初始化 git 并提交所有内容。接下来,创建一个新的 heroku app 并把所有内容推送到 master 分支。

如果你在操作中遇到任何问题,可参考我之前的文章heroku 文档

由于篇幅限制,请点击这里继续阅读。



原文作者:Ibtesam Ansari
原文链接:https://medium.com/flutter-community/realtime-chat-app-one-to-one-using-flutter-socket-io-node-js-acd4152c6a0
推荐阅读
相关专栏
开发者实践
186 文章
本专栏仅用于分享音视频相关的技术文章,与其他开发者和声网 研发团队交流、分享行业前沿技术、资讯。发帖前,请参考「社区发帖指南」,方便您更好的展示所发表的文章和内容。