創(chuàng)建websocket.js
let Socket = ''
let setIntervalWesocketPush = null
/**
* 建立websocket連接
* @param {string} url ws地址
*/
export const createSocket = url => {
Socket && Socket.close()
if (!Socket) {
console.log('建立websocket連接')
Socket = new WebSocket(url)
Socket.onopen = onopenWS
Socket.onmessage = onmessageWS
Socket.onerror = onerrorWS
Socket.onclose = oncloseWS
} else {
console.log('websocket已連接')
}
}
/**打開WS之后發(fā)送心跳 */
const onopenWS = () => {
sendPing()
}
/**連接失敗重連 */
const onerrorWS = () => {
Socket.close()
clearInterval(setIntervalWesocketPush)
console.log('連接失敗重連中')
if (Socket.readyState !== 3) {
Socket = null
createSocket()
}
}
/**WS數(shù)據(jù)接收統(tǒng)一處理 */
const onmessageWS = e => {
window.dispatchEvent(new CustomEvent('onmessageWS', {
detail: {
data: e.data
}
}))
}
/**
* 發(fā)送數(shù)據(jù)但連接未建立時(shí)進(jìn)行處理等待重發(fā)
* @param {any} message 需要發(fā)送的數(shù)據(jù)
*/
const connecting = message => {
setTimeout(() => {
if (Socket.readyState === 0) {
connecting(message)
} else {
Socket.send(JSON.stringify(message))
}
}, 1000)
}
/**
* 發(fā)送數(shù)據(jù)
* @param {any} message 需要發(fā)送的數(shù)據(jù)
*/
export const sendWSPush = message => {
if (Socket !== null && Socket.readyState === 3) {
Socket.close()
createSocket()
} else if (Socket.readyState === 1) {
Socket.send(JSON.stringify(message))
} else if (Socket.readyState === 0) {
connecting(message)
}
}
/**斷開重連 */
const oncloseWS = () => {
clearInterval(setIntervalWesocketPush)
console.log('websocket已斷開....正在嘗試重連')
if (Socket.readyState !== 2) {
Socket = null
createSocket()
}
}
/**發(fā)送心跳
* @param {number} time 心跳間隔毫秒 默認(rèn)5000
* @param {string} ping 心跳名稱 默認(rèn)字符串ping
*/
export const sendPing = (time = 5000, ping = 'ping') => {
clearInterval(setIntervalWesocketPush)
Socket.send(ping)
setIntervalWesocketPush = setInterval(() => {
Socket.send(ping)
}, time)
}
下載 (也可復(fù)制源碼丁稀,放在本地丘逸,使用方式相同)
npm install @sven0706/websocket -S
使用
// 在main.js或需要使用的地方引入并建立連接
import { createSocket } from '@sven0706/websocket'
createSocket('wss://api.baidu.com')
// 發(fā)送消息
import { sendWSPush } from '@sven0706/websocket'
sendWSPush(data)
// 接收消息
const getsocketData = e => { // 創(chuàng)建接收消息函數(shù)
const data = e && e.detail.data
console.log(data)
}
// 注冊監(jiān)聽事件
window.addEventListener('onmessageWS', getsocketData)
// 在需要的時(shí)候卸載監(jiān)聽事件,比如離開頁面
window.removeEventListener('onmessageWS', getsocketData)
API
僅三個(gè)api, 且一般只需要用到`createSocket`, `sendWSPush`
/**
* 建立websocket連接
* @param {string} url ws地址
*/
createSocket(url)
/**
* 發(fā)送數(shù)據(jù)
* @param {any} message 需要發(fā)送的數(shù)據(jù)
*/
sendWSPush(message)
/**發(fā)送心跳
* @param {number} time 心跳間隔毫秒 默認(rèn)5000
* @param {string} ping 心跳名稱 默認(rèn)字符串ping
*/
sendPing()
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者