1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- import website from '~src/config/index'
- import { isNullES } from 'js-fast-way'
- // 长链接推送插件
- export default class HcSocket {
- static socket = null
- static create(data, change) {
- const socket = new WebSocket(website.socket + data)
- socket.onopen = function () {
- console.log('websocket 链接成功')
- }
- socket.onclose = function () {
- console.log('websocket 链接已断开')
- }
- socket.onmessage = function ({ data }) {
- if (typeof change !== 'function') {
- return false
- } else {
- change(JSON.parse(data))
- }
- }
- socket.onerror = function ({ data }) {
- console.log('websocket 发生错误:', data)
- }
- this.socket = socket
- }
- //发送消息
- static async send(data) {
- const is_socket = await this.isSocket()
- if (!is_socket) return false
- this.socket.send(data)
- }
- //链接是否存在
- static async isSocket(i = 0) {
- let _this = this
- return new Promise((resolve) => {
- if (isNullES(_this.socket)) {
- if (i <= 30) {
- setTimeout(async () => {
- i++
- resolve(await _this.isSocket(i))
- }, 1000)
- } else {
- resolve(false)
- }
- } else {
- resolve(true)
- }
- })
- }
- }
|