1.websocket 方法
import { message } from 'ant-design-vue'
import i18n from '@/langs/index.js'
let socket = null
let handleMessage = null
let handleErr = null
function initSocket(url) {
if (typeof WebSocket === 'undefined') {
message.error(i18n.t('public.websocket.noWebSocket'))
}
socket = new WebSocket(url)
socket.onopen = (e) => {
socketOnOpen()
}
socket.onmessage = (e) => {
socketOnMessage(e)
}
socket.onerror = (e) => {
socketOnError()
}
socket.onclose = (e) => {}
}
function socketOnOpen(e) {}
function socketOnMessage(e) {
if (handleMessage) {
handleMessage(JSON.parse(e.data))
}
}
function socketOnError(e) {
if (handleErr) {
handleErr()
}
}
function socketSend(data) {
setTimeout(() => {
if (socket.readyState === 1) {
socket.send(JSON.stringify(data))
} else if (socket.readyState === 3) {
message.error(i18n.t('public.websocket.connectFailed'))
}
}, 500)
}
export function connectSocket(url, data, handleData, handleError) {
handleMessage = null
handleErr = null
if (handleData) {
handleMessage = handleData
}
if (handleError) {
handleErr = handleError
}
initSocket(url)
socketSend(data)
}
export function closeSocket() {
if (socket) {
socket.close()
}
}
2. 使用
import { connectSocket, closeSocket } from './socket.js'
convert() {
let data = {}
let socketUrl = ''
connectSocket(socketUrl, data, this.handleMessage)
},
handleMessage(data) {
console.log(data)
}
|