websocket封装
创建 websocket.js 文件
import Vue from 'vue';
import store from '@/store'
import {
Message } from 'element-ui';
/**
* @param {object} webSocketInfo 创建用户信息
* @param {string} WebSocketUrl websocket连接地址
* @param {string} webSocketType 创建用户类型 service:客服 customer:客户
* @param {function} webSocketInterval 定时器
*/
let webSocketInfo, WebSocketUrl, webSocketType
let webSocketInterval = null
let webSocketVisitorList = []
let webSocketMsgList = []
export function createWebSocket(type, webSocketName) {
webSocketType = type
if (webSocketType == 'service') {
/** 客服 */
WebSocketUrl = '客服链接地址'
webSocketInfo = {
state: {
agentId: webSocketName,
department: '1',
},
clientType: 1
}
} else {
/** 客户 */
WebSocketUrl = '客户链接地址'
webSocketInfo = {
fromUser: webSocketName,
createTime: new Date().getTime(),
isFirstSend: 1
}
}
if (WebSocketUrl == '') {
Message.warning('未设置服务器地址');
} else {
if ("WebSocket" in window || 'MozWebSocket' in window) {
/** 浏览器支持 */
Vue.$webSocket = new WebSocket(WebSocketUrl);
Vue.$webSocket.onopen = webSocketOnopen;
Vue.$webSocket.onmessage = webSocketOnMessage;
Vue.$webSocket.onclose = webSocketOnClose;
Vue.$webSocket.onerror = webSocketOnError;
} else {
/** 浏览器不支持 */
Message.warning('您的浏览器不支持 WebSocket!');
}
}
}
/** webSocket 创建成功 */
function webSocketOnopen(e){
WebSocketSendMassage(webSocketInfo);
/** 客服端每隔30秒钟发送一次心跳,避免websocket连接因超时而自动断开*/
if (webSocketType == 'service') {
webSocketInterval = window.setInterval(function(){
if(Vue.$webSocket!=null){
WebSocketSendMassage('heartbeat - 与后端商议好传输的数据');
}
},30000);
}
console.log('webSocket => 连接成功');
}
/**
* webSocket 发送信息
* *@param {string} sendManually 用于区分是否创建时发送与发送者
* */
export function WebSocketSendMassage(value, sendManually = '') {
if (Vue.$webSocket != null || Vue.$webSocket != undefined) {
Vue.$webSocket.send(JSON.stringify(value));
}
if (sendManually != '')