websocket 是長連接,受網絡限制比較大
ajax輪詢的原理是:讓瀏覽器隔個幾秒就發送一次請求,詢問服務器是否有新信息。
用websocket主要原因是不需要用定時器幾秒去請求一次接口查看進度
附代碼:
<template>
<div>
<a-card :bordered="false">
<!-- 操作按鈕區域 -->
<div style="margin-top:20px;width: 340px;">
<a-progress :percent="progress" :status="status" />
</div>
<div style="margin-top:20px;">
<a-button type="primary" @click="sendMessage()">發消息</a-button>
</div>
</a-card>
</div>
</template>
<script>
export default {
data() {
return {
disabled: false,
status: 'active',
progress: 0,
count: 0,
no: 0,
path: 'xxxxx', //接口地址
socket: ''
}
},
watch: {
progress() {
console.log(this.progress, '------')
}
},
mounted() {
this.init(this.path)
},
methods: {
init(path) {
if (typeof WebSocket === 'undefined') {
alert('您的瀏覽器不支持socket')
} else {
// 實例化socket
this.socket = new WebSocket(path)
// 監聽socket連接
this.socket.onopen = this.open
// 監聽socket錯誤信息
this.socket.onerror = this.error
// 監聽socket消息
this.socket.onmessage = this.getMessage
}
},
//實現化WebSocket對象
//指定要連接的服務器地址與端口建立連接
//注意ws、wss使用不同的端口。我使用自簽名的證書測試,
//無法使用wss,瀏覽器打開WebSocket時報錯
//ws對應http、wss對應https。
//連接打開事件
open: function() {
console.log('Socket 已打開,socket連接成功')
},
//發生了錯誤事件
error: function() {
console.log('連接錯誤')
},
//收到消息事件
getMessage: function(msg) {
console.log(msg.data) //接收到的數據
let obj = JSON.parse(msg.data)
if (
typeof obj == 'object' &&
Object.prototype.toString.call(obj).toLowerCase() == '[object object]' &&
!obj.length
) {
// console.log('是JSON對象')
this.no = obj.no
this.count = obj.count
this.progress = parseInt((this.no / this.count) * 100)
this.status = 'active'
if (this.progress == 100) {
this.status = 'success'
this.$message.success('成功!')
setTimeout(() => {
this.$router.go(0)
}, 4000)
}
}
},
sendMessage: function() {
this.disabled = !this.disabled
this.socket.send(JSON.stringify(this.obj))
},
//連接關閉事件
close: function() {
console.log('socket已經關閉')
}
},
destroyed() {
console.log('離開')
// 銷燬監聽
this.socket.onclose = this.close()
}
}
</script>
<style lang="less" scoped>
</style>
想要了解更多事件和屬性等相關信息可以看這些
https://www.runoob.com/html/html5-websocket.html
http://www.ruanyifeng.com/blog/2017/05/websocket.html