一文詳解websocket在vue2中的封裝使用
websocket在vue2中的封裝使用
先說需求: 頁(yè)面中有websocket連接,進(jìn)入的時(shí)候發(fā)送參數(shù)到后端,后端發(fā)送消息, 離開頁(yè)面時(shí)發(fā)送參數(shù)至后端,后端停止發(fā)送消息,不得斷開連接, 下一次進(jìn)入時(shí)頁(yè)面時(shí)不用再次連接。
實(shí)現(xiàn)思路:
- 因?yàn)槭侨诌B接一個(gè)websocket,所以這里采用單例模式
- 也是因?yàn)榉庋b的原因,頁(yè)面中肯定是直接拿不到onmessage中返回的數(shù)據(jù), 所以這里采用發(fā)布訂閱模式來做
完整代碼在最后,不想看我廢話的可以直接扒拉了
步驟
步驟就是: 連接,頁(yè)面發(fā)送消息,接收消息,over ~
首先定義連接websocket的方法
export default class SocketService {
constructor(url){
this.url = url
},
connect() {
//判斷瀏覽器是否支持websocket
if (!window.WebSocket) {
return console.log("您的瀏覽器不支持WebSocket");
}
url,
//連接websocket
this.ws = new WebSocket(this.url);
//監(jiān)聽websocket各種狀態(tài)
this.ws.onopen = () => {};
this.ws.onclose = () => {};
this.ws.onerror = () => {};
this.ws.onmessage = (e) => {};
}
}
我們先讓socket連接上叭
export default class SocketService {
constructor(url, againConnect = true){
this.url = url
this.againConnect = againConnect;
},
ws = null; // 和服務(wù)端連接的socket對(duì)象
url; //地址
againConnect; //標(biāo)識(shí)斷開是否重連
connected = false; // 標(biāo)識(shí)是否連接成功
sendRetryCount = 0; // 記錄重試的次數(shù)
connectRetryCount = 0; // 重新連接嘗試的次數(shù)
connect() {
//判斷瀏覽器是否支持websocket
if (!window.WebSocket) {
return console.log("您的瀏覽器不支持WebSocket");
}
url,
//連接websocket
this.ws = new WebSocket(this.url);
//監(jiān)聽websocket各種狀態(tài)
this.ws.onopen = () => {
//連接上后所有標(biāo)識(shí)清零
this.connected = true;
this.connectRetryCount = 0;
};
this.ws.onclose = () => {
//連接關(guān)閉
this.connected = false;
this.connectRetryCount++;
if (this.againConnect) {
//重連
setTimeout(() => {
this.connect();
}, 500 * this.connectRetryCount);
} else {
//不重連的操作
sessionStorage.clear();
localStorage.clear();
message.error("登錄超時(shí)");
router.push("/");
}
};
this.ws.onerror = () => {
//連接失敗
this.connected = false;
this.connectRetryCount++;
if (this.againConnect) {
setTimeout(() => {
this.connect();
}, 500 * this.connectRetryCount);
}
};
this.ws.onmessage = (e) => {
console.log(e)
};
},
unSubscribe() {}
send(){
//發(fā)送消息的方法
}
}
那么我們要怎么給后端發(fā)送消息呢,發(fā)送了消息之后我們又該怎樣才能在頁(yè)面中接收到消息呢?
在send方法中接收一個(gè)回調(diào)函數(shù),
在message中調(diào)用,
subscribeList = {}; //記載回調(diào)函數(shù)
idList = [];
send(data, callback) {
//判斷此時(shí)有沒有ws
if (!this.ws) {
this.connect();
this.send(data, callback);
} else {
// 判斷此時(shí)此刻有沒有連接成功
if (this.connected) {
this.sendRetryCount = 0;
this.ws.send(JSON.stringify(data));
if (data.type === "sub") {
//存儲(chǔ)id
this.idList.push(data.id);
//存儲(chǔ)回調(diào)函數(shù),
if (!this.subscribeList[data.id]) {
this.subscribeList[data.id] = [callback];
} else {
this.subscribeList[data.id].push(callback);
}
}
} else {
this.sendRetryCount++;
setTimeout(() => {
this.send(data, callback);
}, this.sendRetryCount * 500);
}
}
}
connect(){
......
this.ws.onmessage = (e) => {
let { payload, requestId, type } = JSON.parse(e.data);
if (type === "error") {
console.log("出錯(cuò)了");
}
if (this.subscribeList[requestId]) {
if (type === "complete") {
console.log("完成了");
} else if (type === "result") {
this.subscribeList[requestId].forEach((item) =>
item.call(this, payload)
);
}
}
};
}
//銷毀回調(diào)函數(shù)
unSubscribe() {
//停止消息發(fā)送
this.idList.forEach((item) => {
this.send({ id: item, type: "unsub" });
delete this.subscribeList[item];
});
this.idList = [];
}
- sub標(biāo)識(shí)發(fā)送消息, unsub標(biāo)識(shí)停止發(fā)送消息
- id為事件的標(biāo)識(shí)符
現(xiàn)在解決了頁(yè)面中接收消息的問題,那么怎么保證離開頁(yè)面,回到頁(yè)面,使用的是同一個(gè)websocket呢,如果實(shí)例化這個(gè)類的話,那么每次進(jìn)入都會(huì)實(shí)例化SocketService,
es6的class中有取值函數(shù)和存值函數(shù), 具體使用請(qǐng)看這里:
Class 的基本語(yǔ)法 - ES6 教程 - 網(wǎng)道 (wangdoc.com)
instance = null;
static get Instance() {
if (!this.instance) {
this.instance = new SocketService(false);
}
return this.instance;
}
- 使用getter,來拿取class中的instance,拿取的時(shí)候設(shè)置攔截該行為,判斷instance有沒有值,沒有值就實(shí)例化SocketService給instance,返回instance,
頁(yè)面中使用方式
import SocketService from "@/websocket/websocket";
mounted() {
this.ws = SocketService.Instance;
this.ws.send(
{
id: "11111",
topic: "/xxx/xxx",
parameter: {},
type: "sub",
},
this.Callback
);
}
destroyed() {
this.ws.unSubscribe();
},
methods:{
Callback(data) {
console.log(data);
},
}
看到這里了,不妨給個(gè)小心心叭
在vue中的封裝
export default class SocketService {
constructor(againConnect = true, url) {
this.url = url;
this.againConnect = againConnect;
}
instance = null; //頁(yè)面中使用的SocketService實(shí)例
ws = null; // 和服務(wù)端連接的socket對(duì)象
url; //地址
againConnect; //斷開是否重連
connected = false; // 標(biāo)識(shí)是否連接成功
sendRetryCount = 0; // 記錄重試的次數(shù)
connectRetryCount = 0; // 重新連接嘗試的次數(shù)
//單例模式保證只有一個(gè)SocketService實(shí)例
static get Instance() {
if (!this.instance) {
this.url = '......'
this.instance = new SocketService(false, url);
}
return this.instance;
}
// 定義連接服務(wù)器的方法
connect() {
// 這里判斷你的瀏覽器支不支持websocket
if (!window.WebSocket) {
return console.log("您的瀏覽器不支持WebSocket");
}
this.ws = new WebSocket(this.url);
//連接上了
this.ws.onopen = () => {
this.connected = true;
// 重置重新連接的次數(shù)
this.connectRetryCount = 0;
};
//連接關(guān)閉了,設(shè)置標(biāo)識(shí)值為false,
this.ws.onclose = () => {
this.connected = false;
this.connectRetryCount++;
if (this.againConnect) {
setTimeout(() => {
this.connect();
}, 500 * this.connectRetryCount);
} else {
sessionStorage.clear();
localStorage.clear();
message.error("登錄超時(shí)");
router.push("/");
}
};
this.ws.onerror = () => {
console.log("socket連接失敗");
this.connected = false;
this.connectRetryCount++;
if (this.againConnect) {
setTimeout(() => {
this.connect();
}, 500 * this.connectRetryCount);
}
};
this.ws.onmessage = (e) => {
let { payload, requestId } = JSON.parse(e.data);
if (this.subscribeList[requestId]) {
this.subscribeList[requestId].forEach((item) =>
item.call(this, payload)
);
}
};
}
//銷毀回調(diào)函數(shù)
unSubscribe() {
//停止消息發(fā)送
this.idList.forEach((item) => {
this.send({ id: item, type: "unsub" });
delete this.subscribeList[item];
});
this.idList = [];
}
subscribeList = {}; //記載回調(diào)函數(shù)
idList = [];
// 發(fā)送數(shù)據(jù)的方法
send(data, callback) {
//判斷此時(shí)有沒有ws
if (!this.ws) {
this.connect();
this.send(data, callback);
} else {
// 判斷此時(shí)此刻有沒有連接成功
if (this.connected) {
this.sendRetryCount = 0;
this.ws.send(JSON.stringify(data));
if (data.type === "sub") {
//存儲(chǔ)id
this.idList.push(data.id);
//存儲(chǔ)回調(diào)函數(shù),
if (!this.subscribeList[data.id]) {
this.subscribeList[data.id] = [callback];
} else {
this.subscribeList[data.id].push(callback);
}
}
} else {
this.sendRetryCount++;
setTimeout(() => {
this.send(data, callback);
}, this.sendRetryCount * 500);
}
}
}
}以上就是一文詳解websocket在vue2中的封裝使用的詳細(xì)內(nèi)容,更多關(guān)于vue2封裝websocket的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue+element-ui+axios多文件上傳的實(shí)現(xiàn)并顯示整體進(jìn)度
這篇文章主要介紹了vue+element-ui+axios多文件上傳的實(shí)現(xiàn)并顯示整體進(jìn)度,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04
前端虛擬滾動(dòng)列表實(shí)現(xiàn)代碼(vue虛擬列表)
前端的性能瓶頸那就是頁(yè)面的卡頓,當(dāng)然這種頁(yè)面的卡頓包含了多種原因,下面這篇文章主要給大家介紹了關(guān)于前端虛擬滾動(dòng)列表實(shí)現(xiàn)的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-06-06
element中Steps步驟條和Tabs標(biāo)簽頁(yè)關(guān)聯(lián)的解決
這篇文章主要介紹了element中Steps步驟條和Tabs標(biāo)簽頁(yè)關(guān)聯(lián)的解決,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
vue使用高德地圖實(shí)現(xiàn)添加點(diǎn)標(biāo)記和獲取點(diǎn)擊位置信息的示例代碼
這篇文章主要介紹了vue使用高德地圖實(shí)現(xiàn)添加點(diǎn)標(biāo)記和獲取點(diǎn)擊位置信息的示例代碼,文中補(bǔ)充介紹了高德vue-amap使用(一)標(biāo)記點(diǎn)位獲取地址及經(jīng)緯度,本文結(jié)合示例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧2024-01-01
vue項(xiàng)目發(fā)布有緩存正式環(huán)境不更新的解決方案
vue項(xiàng)目每次發(fā)布新版本后,測(cè)試人員都要強(qiáng)制刷新才能更新瀏覽器代碼來驗(yàn)證bug,下面這篇文章主要給大家介紹了關(guān)于vue項(xiàng)目發(fā)布有緩存正式環(huán)境不更新的解決方案,需要的朋友可以參考下2024-03-03
在Vue中使用動(dòng)態(tài)import()語(yǔ)法動(dòng)態(tài)加載組件
在Vue中,你可以使用動(dòng)態(tài)import()語(yǔ)法來動(dòng)態(tài)加載組件,動(dòng)態(tài)導(dǎo)入允許你在需要時(shí)異步加載組件,這樣可以提高應(yīng)用程序的初始加載性能,本文給大家介紹在Vue中使用動(dòng)態(tài)import()語(yǔ)法動(dòng)態(tài)加載組件,感興趣的朋友一起看看吧2023-11-11

