import WsSocket from '@/utils/ws/ws-socket' import { getToken } from '@/utils/auth' import { Notification } from 'element-ui' /** * SocketInstance 连接实例 * * 注释: 所有 WebSocket 消息接收处理在此实例中处理 */ class SocketInstance { /** * WsSocket 实例 */ socket /** * SocketInstance 初始化实例 */ constructor() { this.socket = new WsSocket( () => { const token = getToken() if (token === null || token === '') { return null } else { return 'ws://push.reghao.cn/ws/push?token=' + token } }, { onError: evt => { console.log('Websocket 连接失败回调方法') }, // Websocket 连接成功回调方法 onOpen: evt => { // 更新 WebSocket 连接状态 console.log('ws 连接成功') }, // Websocket 断开连接回调方法 onClose: evt => { // 更新 WebSocket 连接状态 console.log('ws 连接断开') } } ) this.registerEvents() } // 连接 WebSocket 服务 connect() { this.socket.connection() } /** * 注册回调消息处理事件 */ registerEvents() { this.socket.on('heartbeat', data => {}) this.socket.on('censorVideo', data => { console.log('----------') console.log(data) Notification({ title: '友情提示', message: data, type: 'warning', duration: 3000 }) }) this.socket.on('event_error', data => { Notification({ title: '友情提示', message: data.message, type: 'warning' }) }) } /** * 聊天发送数据 * * @param {Object} mesage */ send(mesage) { this.socket.send(mesage) } /** * 推送消息 * * @param {String} event 事件名 * @param {Object} data 数据 */ emit(event, data) { this.socket.emit(event, data) } } export default new SocketInstance()