vue socket.io实现一个简易聊天室_前端实现简单聊天室的需求具体是什么-程序员宅基地

技术标签: vue  前端  nodejs  javascript  

     vue vuex elementUi socket.io实现一个简易的在线聊天室,提高自己在对vue系列在项目中应用的深度。因为学会一个库或者框架容易,但要结合项目使用一个库或框架就不是那么容易了。功能虽然不多,但还是有收获。设计和实现思路较为拙劣,恳请各位道友指正

可以达到的需求

  • 能查看在线用户列表
  • 能发送和接受消息

使用到的框架和库

  • socket.io做为实时通讯基础
  • vuex/vue:客户端Ui层使用
  • Element-ui:客户端Ui组件

类文件关系图

服务端:

客户端:

服务端实现

    实现聊天服务器的相关功能,包含通讯管道的创建、用户加入、消息的接受与转发等。

一、通讯服务建立

    build/server-config.js:聊天服务器的入口

let socketIo = require('socket.io');
let express = require('express'); 
let cxt = require('../src/services-server');

let httpPort = 9001;
let channelId = 1
let app = express();

app.get('/',function(req,res){
    res.send('启动成功:'   httpPort);
});
 
let server = require('http').createServer(app);
let io = socketIo(server);
io.on('connection',function(socket){ 
    console.log('有客户端连接');
    cxt.createChannel(channelId  ,socket)
});
server.listen(httpPort); //用server连接
console.log('io listen success !! '   httpPort);
  • 通过express创建一个server对象,然后利用socketIo创建io对象
  • 然后通过io的on方法监听connection事件
  • 当有客户端连接时,触发connection事件,县立即调用"服务端上下文(后面简称cxt)"的createChannel方法创建一个管道,此时的管道上是没有用户信息的。

二、创建上下文(服务端上下文)

实现一个聊天室上下文,包含:用户、房间、消息、管道等数组,所以代码都在service-server目录中。

  • index.js:聊天室服务端上下文创建入口,创建context,并初始化房间到上下文中。
  • context.js:聊天室服务端上下文类,用户、房间、消息、管道等类在此中做集中管理。
  • room目录:包含房间和房间集合的实现
  • channel:服务端与客户端通讯的管道类
    结合"通讯服务建立"中的connectiong事件的触,其后转到cxt.createChannel方法
createChannel (id, socket) {
    let channel = new Channel(id, socket, this)
    channel.init()
    channel.index = this.channels.length
    this.channels.push(channel)
}

此时会创建一个管道实例,然后初始化管道实例,并将管道添加到管道数组中。以下是初始化管道实例的代码:

init () {
    let self = this
    let roomInfo = this.cxt.room.collections[0]
    this.roomInfo = roomInfo
    this.socket.join('roomId'   roomInfo.id)
    this.socket.emit(this.cxt.eventKeys.emit.sendRooms, roomInfo) /* send出去一个默认的房间 */
    this.socket.on(this.cxt.eventKeys.client.registerUser, function (id, name) {
      console.log(id   '-'   name   '--'   self.id)
      self.cxt.createUserById(id, name, self.id)
    }) /** 新用户注册 */
    this.socket.on(this.cxt.eventKeys.client.newMsg, function (msg) { /** 发送消息 */
      self.notifyMsg(msg)
      console.log(msg)
      self.cxt.addMsg(msg)
    })
    this.socket.on(this.cxt.eventKeys.client.closeConn, function () {
      console.log(self.id   '--关闭连接')
      self.cxt.remove(self)
    })
    this.sendUsers()
}

在初始化管道实例时做了如下事件:

  • 将通讯socket添加一个到房间中,方便后期好广播消息
  • 向当前连接上来的socket发送房间信息,设定为第一个房间
  • 监听三个事件:用户注册、新消息、关闭连接。此处都要逻辑处理,可以参考源码。

客户端实现

    主要实现连接服务、注册用户、发送和接受消息的功能。首先以main.js为入口,且需要先装配好vue相关配件,如vuex、ElemUi、客户端通讯管道等,然后创建vue实例和连接消息服务器,代码如下:

import '../node_modules/bootstrap/dist/css/bootstrap.css'
import Vue from 'vue'
import ElemUi from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
import App from './App'
import * as stores from './store'
import { Keys } from './uitls'
import { getCxt } from './services-client'

let initRoomInfo = Keys.SETROOMINFO
Vue.use(ElemUi)
/* eslint-disable no-new */
new Vue({
  store: stores.default,
  el: '#app',
  template: '<App/>',
  components: { App },
  created: function () {
    let self = this
    getCxt().createIo(this, function (roomInfo) {
      stores.busCxt.init() /** 初始化view与service层的交互层(业务层) */
      self.$store.dispatch(initRoomInfo, roomInfo)
      getCxt().refUsers(function (users) {
        stores.busCxt.userCxt.refUsers(users)
      })
    })
  }
})

一、与服务端的通讯

service-client目录中实例的与消息服务器通讯,其中包含创建用户、接受和发送消息等。一个客户端只能拥有一个消息管道,以下代码是消息管理的创建:

import * as io from 'socket.io-client'
import Context from './context'

let eventKeys = require('../services-uitls/event.keys')
let url = 'http://localhost:9001/'
let cxt = null

export function getCxt () {
  if (cxt == null) {
    cxt = new Context(url, eventKeys, io)
  }
  return cxt
}

在main.js中的vue实例的created勾子中调用了Context的createIo实例方法,用于创建一个与消息服务器的连接,并接受其中房间发送回来的房间信息。然后就初始化业务层。

二、vuex的结合

     在store目录中实现,包含了vuex类相关的实现,还有业务层的实现。其中业务层会引用"客户端通讯管道",而vuex实现类有可能会引用业务层相关实现类,以此实现ui到"消息服务器"的通讯。 store/index.js代码如下:

import Vuex from 'vuex'
import Vue from 'vue'

import RoomViewCxt from './room/roomViewCxt'
import UserViexCxt from './userViewCxt'
import MsgViewCxt from './msg/msgViewCxt'
import BusCxt from './indexForBus'

let _busCxt = new BusCxt()

let _rvCxt = new RoomViewCxt()
let _uvCxt = new UserViexCxt(_busCxt.userCxt)
let _mvCxt = new MsgViewCxt()

let opt = {
  state: null,
  getters: null,
  mutations: null,
  actions: null
}
_rvCxt.use(opt)
_uvCxt.use(opt)
_mvCxt.use(opt)

Vue.use(Vuex)

let store = new Vuex.Store(opt)
export default store
export const busCxt = _busCxt /** 业务处理上下文 */
export function getBusCxt () {
  return _busCxt
}

三、组件

组件只实现了 用户注册、主界面容器、消息发送和消息接受等。组件只会引用store目录中相关类,不会直接引用管道类。

  • Login.vue:用户注册组件
  • HChat.vue:主界面容器组件
  • Message/MsgWriter.vue:发送消息组件
  • Message/MsgList.vue:接受和显示消息列表组件

如何运行实例

  • 下载源码
  • cnpm run install 安装所有的依赖
  • npm run sokcetIo 启动消息服务器
  • npm run dev 启动客户端
  • 示例截图


更多专业前端知识,请上 【猿2048】www.mk2048.com
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_29069777/article/details/102522598

智能推荐

web应用托管_自托管的免费发票应用-FusionInvoice-程序员宅基地

文章浏览阅读438次。web应用托管Note that around the exact time of this article’s publication, FusionInvoice 2 was released as commercial software, and is based on Laravel instead of CodeIgniter like previous versions. It is,..._]fusion怎么处理电子(非纸质)发票?

react 组件添加样式_如何通过4个简单的步骤将CSS模块样式表添加到React组件-程序员宅基地

文章浏览阅读252次。react 组件添加样式Let’s say you’d like to add a CSS Modules Stylesheet to your project. You can find Create React App’s guidance here, but essentially — and as the guidance states — CSS Modules let you use ..._react在自定义的组件上增加样式类

如何在Google和其他高科技公司获得软件工程师职位-程序员宅基地

文章浏览阅读510次。by YK Sugi 由YK Sugi 如何在Google和其他高科技公司获得软件工程师职位 (How to Get a Software Engineer Job at Google and Other Top Tech Companies)Hi everyone! 嗨,大家好! I’ve already talked about how I personally got a softw..._获得谷歌的软件工程师职位英语

steam密码查看_如何查看和清除Steam中的先前别名-程序员宅基地

文章浏览阅读3.5k次。steam密码查看Steam lets you set your name to anything within its terms of service. This can make it difficult to find people—even if they’re already on your friends list. Find out who’s who by checking al..._steam密码查看

spark和java类型转化时报错:Caused by: java.lang.ClassCastException: scala.collection.mutable_scala.collection.mutable.wrappedarray$ofref is not-程序员宅基地

文章浏览阅读1.3k次。错误:Caused by: java.lang.ClassCastException: scala.collection.mutable.WrappedArray$ofRef cannot be cast to java.util.List分析:这个问题,一般是在sparksql中做row转换时候出错,最好一步步排错。这里要说的是, row:Row是先做了一次强制类型转换(asInstanceOf),row的实际类型是Seq[T],但是不能用Array[T],否则就会出现各种scala和java的类_scala.collection.mutable.wrappedarray$ofref is not a valid external type for

kconfig_对自己的项目使用kconfig-程序员宅基地

文章浏览阅读1.3k次。kconfig 介绍 (Intro)Every Linux professional write scripts. Someеimes light, linear. Sometimes complex script with functions and libs(yes, you can write your bash-library for use in other scripts). 每个..._kconfig 应用程序

随便推点

解决正在等待响应_解决一些等待问题-程序员宅基地

文章浏览阅读4k次。解决正在等待响应 背景 (Background) On occasion, I’ll see waits that exceed what I expect well above normal and a few of them have some architecture and standards to consider following when troubleshooting, ..._正在等待某某某的响应

outlook邮件恢复字体_如何更改Outlook 2013中邮件列表中使用的字体大小-程序员宅基地

文章浏览阅读2.1k次。outlook邮件恢复字体Outlook 2013 allows you to customize the font used to display the sender’s name, subject, date received, and size of each message in your message list. Maybe you want to just change the s..._how to change the font size of outlook

使用django-social-auth获取用户数据-程序员宅基地

文章浏览阅读285次。Recently we had to add support for social networks login to an application we are developing and we chose django-social-auth to work with. It is a well documented and easy to use django application fo..._django social auth

vue带缩略图的轮播图插件_带有缩略图轮播的自适应图像库-程序员宅基地

文章浏览阅读2.5k次。vue带缩略图的轮播图插件View demo 查看演示Download Source 下载源Today we want to show you how to create a responsive image gallery with a thumbnail carousel using Elastislide. Inspired by Twitter’s ..._jquery 实现照片流

debian 查看日志_如何使用Debian 10上的日志集中日志-程序员宅基地

文章浏览阅读4.8k次。debian 查看日志 介绍 (Introduction)System logs are an extremely important component of managing Linux systems. They provide an invaluable insight into how the systems are working and also how they are bein..._debian中日志服务

symfony 查询数据_Symfony2中的数据装置-程序员宅基地

文章浏览阅读222次。symfony 查询数据Back when I first started to learn Symfony (1.x) with its Jobeet project, I thought the ability to load a bunch of test data into the database very useful. 回到我最初通过Jobeet项目学习Symfony(1.x)时,..._symfony 数组字段查询