vue使用websocket概念及示例
概念部分:
1,WebSocket 是 HTML5 提供的 TCP 連接上進行全雙工通訊的協(xié)議。一次握手之后,服務(wù)器和客戶端可以互相主動通信,雙向傳輸數(shù)據(jù)。
2,瀏覽器想服務(wù)器發(fā)送請求,建立連接之后,可通過send()方法想服務(wù)器發(fā)送數(shù)據(jù),并通過message事件接受服務(wù)器返回的數(shù)據(jù)。
使用示例
<script>
export default {
mounted() {
this.connectWebsocket();
},
methods: {
connectWebsocket() {
let websocket;
if (typeof WebSocket === "undefined") {
console.log("您的瀏覽器不支持WebSocket");
return;
} else {
let protocol = "ws";
let url = "";
if (window.localtion.protocol == "https:") {
protocol = "wss";
}
// `${protocol}://window.location.host/echo`;
url = `${protocol}://localhost:9998/echo`;
// 打開一個websocket
websocket = new WebSocket(url);
// 建立連接
websocket.onopen = () => {
// 發(fā)送數(shù)據(jù)
websocket.send("發(fā)送數(shù)據(jù)");
console.log("websocket發(fā)送數(shù)據(jù)中");
};
// 客戶端接收服務(wù)端返回的數(shù)據(jù)
websocket.onmessage = evt => {
console.log("websocket返回的數(shù)據(jù):", evt);
};
// 發(fā)生錯誤時
websocket.onerror = evt => {
console.log("websocket錯誤:", evt);
};
// 關(guān)閉連接
websocket.onclose = evt => {
console.log("websocket關(guān)閉:", evt);
};
}
}
}
};
</script>
以上就是vue使用websocket概念及示例的詳細內(nèi)容,更多關(guān)于vue使用websocket的資料請關(guān)注腳本之家其它相關(guān)文章!
- 一文詳解websocket在vue2中的封裝使用
- Vue項目中Websocket的使用實例
- 前端之vue3使用WebSocket的詳細步驟
- vue3.0中使用websocket,封裝到公共方法的實現(xiàn)
- vue3+ts+Vuex中使用websocket協(xié)議方式
- Vue項目使用Websocket大文件FileReader()切片上傳實例
- vue項目使用websocket連接問題及解決
- Vue?websocket封裝實現(xiàn)方法詳解
- vue基于websocket實現(xiàn)智能聊天及吸附動畫效果
- Flask使用SocketIO實現(xiàn)WebSocket與Vue進行實時推送
- vue+flv.js+SpringBoot+websocket實現(xiàn)視頻監(jiān)控與回放功能
- vue項目中使用websocket的實現(xiàn)
- vue 項目中使用websocket的正確姿勢
- vue實現(xiàn)websocket客服聊天功能
- Vue+Websocket簡單實現(xiàn)聊天功能
- vue使用WebSocket模擬實現(xiàn)聊天功能
- websocket+Vuex實現(xiàn)一個實時聊天軟件
- 使用WebSocket+SpringBoot+Vue搭建簡易網(wǎng)頁聊天室的實現(xiàn)代碼
相關(guān)文章
vite+vue3搭建的工程實現(xiàn)批量導(dǎo)入store的module
這篇文章主要介紹了vite+vue3搭建的工程實現(xiàn)批量導(dǎo)入store的module方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
vuex 第三方包實現(xiàn)數(shù)據(jù)持久化的方法
本文主要介紹了vuex 第三方包實現(xiàn)數(shù)據(jù)持久化的方法,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09
vue中axios的封裝問題(簡易版攔截,get,post)
這篇文章主要介紹了vue中axios的封裝問題(簡易版攔截,get,post),需要的朋友可以參考下2018-06-06
Vue中router.beforeEach與beforeRouteEnter的區(qū)別及說明
這篇文章主要介紹了Vue中router.beforeEach與beforeRouteEnter的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10

