Home >Web Front-end >JS Tutorial >Simple multi-room online group chat implementation method

Simple multi-room online group chat implementation method

小云云
小云云Original
2018-01-04 10:49:273876browse

This article mainly introduces the example of vue+socket.io+express+mongodb to implement a simple multi-room online group chat. It has certain reference value and interested friends can refer to it. Hope it helps everyone.

Project Introduction

Mainly by doing a small project for multi-person online multi-room group chat, to practice the combined use of full-stack technologies.

Project source code: chat-vue-node

Main technology: vue2 family bucket + socket.io + node(express) + mongodb(mongoose)

Environment Configuration: The node and mongodb environment need to be installed and configured; it is recommended to install the Robomogo client to manage mongodb data.

Compile and run:

1. Start the MongoDB service and create a new command line window 1:


mongod

2 .Start the server node and create a new command line window 2:


cd server
node index.js

3. Start the front-end vue page


cd client
cnpm install
npm run dev

Then open localhost:8080 in multiple windows of the browser, register different accounts and log in to conduct multi-user multi-room online chat.

Main effect preview:

Code directory overview


|--chat-vue-node
  |--client        // 前端客户端:基于 vue-cli 搭建的所有聊天页面
  |--server        // 后台服务端
    |--api.js       // express 通过 mongoose 操作 mongodb 数据库的所有接口
    |--db.js       // 数据库初始化、Schema数据模型
    |--index.js      // 后台服务启动入口
    |--package.json
  .gitignore
  README.md

soeket.io Basics

soeket.io The basic functions used in this project are as follows (for details, please see chatGroup.vue and server/index in GitHub. js two file codes):


// 客户端连接
var socket = io.connect('http://localhost:8081')
// 服务端监听到连接
io.on('connection', function(socket){
 // ......
}

// 客户端发送进入房间请求
socket.emit('joinToRoom', data)
// 服务端监听
socket.on('joinToRoom', function (data) {
 // ......
 // 服务端处理进入房间、离开房间
 socket.join(roomGroupId)
 // 有人进入房间,向该群其它的成员发送更新在线成员
 io.sockets.in(roomGroupId).emit('joinToRoom', chat)
 io.sockets.in(roomGroupId).emit('updateGroupNumber', roomNum[roomGroupId])
}

// 客户端发送聊天消息
socket.emit('emitChat', chat)
// 服务端监听并向群内其它人群发该消息
socket.on('emitChat', function (data) {
 let roomGroupId = chat.chatToGroup
 // 向特定的群成员转发消息
 socket.in(roomGroupId).emit('broadChat', chat)
})

Data structure design

There are three main data structure models:


// 用户信息的数据结构模型
const accountSchema = new Schema({
 account: {type: Number},  // 用户账号
 nickName: {type: String},  // 用户昵称
 pass: {type: Number},    // 密码
 regTime: {type: Number}   // 注册时间
})
// 聊天群的数据结构模型:聊天群包含的成员
const relationSchema = new Schema({
 groupAccount: Number,    // 群账号
 groupNickName: String,   // 群昵称
 groupNumber: []       // 群成员
})
// 单个聊天群的聊天消息记录
const groupSchema = new Schema({
 account: Number,      // 聊天者的账号
 nickName: String,      // 聊天者的昵称
 chatTime: Number,      // 发消息的时间戳
 chatMes: String,      // 聊天的消息内容
 chatToGroup: Number,    // 聊天的所在群账号
 chatType: String      // 消息类型:进入群、离开群、发消息
})

vue-router routing design

The page routing jumps are all handled by the front-end vue-router, and the page functions Few but complete, only 3: registration login page, personal center page, group chat page


routes: [
 // {path: '/', name: 'Hello', component: Hello},
 {path: '/', redirect: '/login', name: 'Hello', component: Hello},
 {path: '/login', name: 'Login', component: Login},
 {path: '/center', name: 'Center', component: Center},
 {path: '/chatGroup', name: 'ChatGroup', component: ChatGroup}
]
// 未登录时,通过编程式跳去登录页:
router.push({ path: 'login' })

vuex global status

Mainly use vuex to globally manage the login status of personal accounts and the information of the current group chat room:


export default new Vuex.Store({
 state: {
  chatState: {
   account: null,
   nickName: null
  },
  groupState: null  // 点击进群的时候更新
 },
 mutations: {
  updateChatState (state, obj) {
   state.chatState = obj
  },
  updateGroupState (state, obj) {
   state.groupState = obj
  }
 },
 actions: {
  updateChatState ({commit}, obj) {
   commit('updateChatState', obj)
  },
  updateGroupState ({commit}, obj) {
   commit('updateGroupState', obj)
  }
 },
 getters: {
  getChatState (state) {
   return state.chatState
  },
  getGroupState (state) {
   return state.groupState
  }
 }
})

Update state globally and obtain state:


// 更新
this.$store.dispatch('updateChatState', {account: null, nickName: null})
// 获取
this.$store.getters.getChatState

Database interface api


module.exports = function (app) {
 app.all("*", function(req, res, next) {
  next()
 })
 // api login 登录
 app.get('/api/user/login', function (req, res) { // ... })
 // api register 注册
 app.get('/api/user/register', function (req, res) { // ... })
 // getAccountGroup 获取可进入的房间
 app.get('/api/user/getAccountGroup', function (req, res) { // ... })
 // getGroupNumber 获取当前房间的群成员
 app.get('/api/user/getGroupNumber', function (req, res) { // ... })
 // api getChatLog 获取当前房间的聊天记录
 app.get('/api/getChatLog', function (req, res) { // ... })
 app.get('*', function(req, res){
  res.end('404')
 })
}

For more detailed implementation, please see the source code chat-vue- node , which retains many comments during development and exploration.

Related recommendations:

Online group chat with iPad-like interface

7 articles about group chat Recommended

Real-time group chat applet development record

The above is the detailed content of Simple multi-room online group chat implementation method. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn