1、寫一個hook函數(shù)
export const useWebsocketToStore = ({ onMessage }): any => {
const url = 'ws:地址' + Math.random()
const onConnected = () => {}
const onDisconnected = () => {}
const onError = () => {}
const onMessageDefault = (ws: WebSocket, event: MessageEvent) => {
try {
const res: ResWSInfoAlarm = JSON.parse(event.data)
console.log(res)
} catch (e) {
console.log(e)
}
}
const { status, data, send, open, close } = useWebSocket(url, {
heartbeat: {
message: 'ping',
interval: 5000,
pongTimeout: 1000,
},
autoReconnect: {
retries: 3,
delay: 1000,
onFailed() {
console.log('Failed to connect WebSocket after 3 retries')
},
},
onConnected: onConnected,
onDisconnected: onDisconnected,
onError: onError,
onMessage: onMessage ?? onMessageDefault,
})
return {
status,
close,
send,
open,
}
}
url
是WebSocket的服務(wù)器地址,其中Math.random()
用于生成一個隨機數(shù),以避免緩存問題。onConnected
、onDisconnected
和onError
是連接建立、斷開和出錯時的回調(diào)函數(shù),你可以根據(jù)實際需求來定義它們。onMessageDefault
是當(dāng)接收到消息時的默認處理函數(shù),在這里將接收到的消息解析為JSON對象,并打印在控制臺上。- 使用
useWebSocket
自定義Hook函數(shù)創(chuàng)建WebSocket連接,傳入連接的URL和一些配置選項,如心跳設(shè)置、自動重連等。- 回了一些狀態(tài)和方法:
status
表示連接狀態(tài),data
保存接收到的數(shù)據(jù),send
用于向服務(wù)器發(fā)送消息,open
用于手動打開連接,close
用于關(guān)閉連接。
2、vue頁面中使用文章來源:http://www.zghlxwxcb.cn/news/detail-698363.html
const webSocketToStore = useWebsocketToStore({
onMessage: (ws: WebSocket, event: MessageEvent) => {
try {
const res: ResWSInfoAlarm = JSON.parse(event.data)
if (res.tenantid === tenantId.value) {
if (res.type === EnumAlarmDialog.info_alarm) {
wsStore.setInfoAlarmCache(res.data)
} else if (res.type === EnumAlarmDialog.hazard_alarm) {
openDialogHazard(res.data as any)
wsStore.initDangerAlarmCache()
} else if (res.type === EnumAlarmDialog.video_alarm) {
openDialogVideo(res.data as any)
wsStore.initVideoAlarmCache()
}
}
} catch (e) {
console.log(e)
}
},
})
?文章來源地址http://www.zghlxwxcb.cn/news/detail-698363.html
- 使用
useWebsocketToStore
自定義Hook函數(shù)創(chuàng)建WebSocket連接,并傳入一個配置對象。- 在配置對象中,指定了
onMessage
回調(diào)函數(shù)。當(dāng)接收到消息時,會進入該回調(diào)函數(shù)進行處理。- 在
onMessage
回調(diào)函數(shù)中,首先嘗試將接收到的消息解析為ResWSInfoAlarm
類型的JSON對象。- 在解析成功后,根據(jù)解析出來的對象的屬性進行判斷和處理,具體邏輯如下:
- 如果解析出來的
tenantid
屬性等于tenantId.value
的值,則進行下一步判斷;- 根據(jù)解析出來的
type
屬性的不同值,執(zhí)行不同的操作。如果type
是EnumAlarmDialog.info_alarm
,則調(diào)用wsStore.setInfoAlarmCache
方法,如果type
是EnumAlarmDialog.hazard_alarm
,則調(diào)用openDialogHazard
方法并調(diào)用wsStore.initDangerAlarmCache
方法,如果type
是EnumAlarmDialog.video_alarm
,則調(diào)用openDialogVideo
方法并調(diào)用wsStore.initVideoAlarmCache
方法。- 如果解析失敗或發(fā)生錯誤,將錯誤信息打印在控制臺上。
到了這里,關(guān)于【vue3】前端應(yīng)用中使用WebSocket與服務(wù)器進行通信并管理連接狀態(tài)。的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!