借鉴于网上资源
一、nodejs+express 构建webSocket服务
1、express server:创建服务文件
2、安装 npm install nodejs-websocket
3、app.js引入以下代码
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
var ws = require("nodejs-websocket");
console.log("开始建立连接...")
var index = null, indexReady = false,num=0;
var server = ws.createServer(function (conn) {
conn.on("text", function (str) {
console.log("收到的信息为:" + str)
if (str === "index") {
index = conn;
}
sendMess();
function sendMess() {
if (index && index.readyState === 1) {
index.sendText(num+'');
num++
setTimeout(sendMess, 10000);
}
}
})
conn.on("close", function (code, reason) {
console.log("关闭连接")
});
conn.on("error", function (code, reason) {
console.log("异常关闭")
});
}).listen(8000)
4、npm start 启动即显示连接成功
二、客户端配置
1、src/store/文件加入news.js
const state = {
unReadNum:0,
wsConnect:false
}
const mutations={
SET_NEWS_COUNT:(state,unReadNum)=>{ //重置未读消息数量
state.unReadNum=unReadNum
},
SET_WS_NEWS_STATUS:(state,wsConnect)=>{ //websocket连接状态
state.wsConnect=wsConnect
}
}
const actions={
getNewsCount({commit},count){
commit('SET_NEWS_COUNT',count)
},
getWsConnectStatus({commit},wsConnect){
commit('SET_WS_NEWS_STATUS',wsConnect)
}
}
export default {
state,
mutations,
actions
}
2 src/untils/ 创建websocket文件
// 引入store,用于管理socket推送来的消息
import store from '../store'
// 封装websocket对象
const WS = {
wsUrl : 'ws://localhost:8000', //接口地址
$ws : null, // webscoket实例
lockReconnect : false, // 避免重复重连
reconnectTimes : 0, // 重连次数
// 初始化webSocket
createWS: function () {
if ('WebSocket' in window) {
this.$ws = new WebSocket(WS.wsUrl)
this.$ws.onopen = this.wsOpen
this.$ws.onmessage = this.wsMessage
this.$ws.onerror = this.wsError
this.$ws.onclose = this.wsClose
} else {
alert('Current browser Not support websocket')
}
},
// webSocket 打开
wsOpen: function () {
if(WS.lockReconnect) return;
WS.$ws.send('index')
WS.lockReconnect=true
store.commit('SET_WS_NEWS_STATUS', true)
console.log('websocket 连接成功')
},
// websocket 接收到服务器消息
wsMessage: function (msg) {
// 每次接收到服务端消息后 重置未读消息数量
store.commit('SET_NEWS_COUNT', msg.data)
console.log('websocket 接收通知')
},
// websocket 发生错误
wsError: function (err) {
console.log('== websocket error ==', err)
// 发生错误重连socket
if (WS.reconnectTimes < 10) {
WS.reconnect()
}
},
// websocket 关闭连接
wsClose: function (event) { //readyState 0:连接尚未建立 1:websocket链接已建立 2、连接正在关闭 3、已经关闭或者不可用
console.log('== websocket close ==', event)
if (WS.$ws && WS.$ws.readyState === 1) {
WS.$ws.close()
store.commit('SET_WS_CONNECT', false)
}
WS.lockReconnect=false
const token = store.getters.token
console.log('token',token)
if (token) {
if (WS.reconnectTimes < 3) { // 设置重连次数为10次
WS.wsReconnect()
}
}
},
wsReconnect: function (){
console.log('Reconnection Socket',WS.reconnectTimes)
if (WS.lockReconnect) return
WS.reconnectTimes++
WS.lockReconnect = true
setTimeout(function () { // 没连接上会一直重连,设置延迟避免请求过多
WS.createWS()
WS.lockReconnect = true
}, 6000)
}
}
export default WS
3、在需要的调用socket连接的组件中引入socket.js文件
import { mapGetters } from 'vuex'
import WsConnection from '@/utils/websoket.js'
export default {
computed: {
...mapGetters([
'unReadNum'
])
},
mounted() {
WsConnection.createWS()
},
destroyed() {
WsConnection.wsClose()
}
}
|