技术标签: vue 前端 nodejs javascript
vue vuex elementUi socket.io实现一个简易的在线聊天室,提高自己在对vue系列在项目中应用的深度。因为学会一个库或者框架容易,但要结合项目使用一个库或框架就不是那么容易了。功能虽然不多,但还是有收获。设计和实现思路较为拙劣,恳请各位道友指正。
服务端:
客户端:
实现聊天服务器的相关功能,包含通讯管道的创建、用户加入、消息的接受与转发等。
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);
实现一个聊天室上下文,包含:用户、房间、消息、管道等数组,所以代码都在service-server目录中。
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()
}
在初始化管道实例时做了如下事件:
主要实现连接服务、注册用户、发送和接受消息的功能。首先以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实例方法,用于创建一个与消息服务器的连接,并接受其中房间发送回来的房间信息。然后就初始化业务层。
在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目录中相关类,不会直接引用管道类。
文章浏览阅读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怎么处理电子(非纸质)发票?
文章浏览阅读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在自定义的组件上增加样式类
文章浏览阅读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..._获得谷歌的软件工程师职位英语
文章浏览阅读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密码查看
文章浏览阅读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
文章浏览阅读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, ..._正在等待某某某的响应
文章浏览阅读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
文章浏览阅读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
文章浏览阅读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 实现照片流
文章浏览阅读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中日志服务
文章浏览阅读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 数组字段查询