1. WebSockets通信的基礎知識
WebSockets是HTML5提供的(de)(de)在WEB應(ying)用程序中客戶端(duan)和(he)服(fu)務(wu)器(qi)端(duan)之間(jian)進行的(de)(de)非(fei)HTTP的(de)(de)通(tong)信機(ji)制(zhi)。可以實現雙向通(tong)信,除非(fei)被顯示關(guan)閉。一旦服(fu)務(wu)器(qi)想發(fa)送數據給客戶端(duan)時,可以通(tong)過(guo)建立的(de)(de)socket將數據推送到客戶端(duan)瀏覽器(qi),無(wu)需重(zhong)新建立連(lian)接。
2. API的使用
- 通(tong)過URL創建websocket對象
var ws = new WebSocket("ws://localhost:8080/socket") - 發送文本數據
ws.send("我是客戶端發送的數據") - 通過ws實例的open事件監聽連接狀態
ws.onopen = function(event){ //開始通信時的處理 }? - 通過ws實例的message事件獲取服務器發送過來的數據
ws.onmessage = function(event){ console.log(event.data) }? -
通過ws實例的close事件(jian)來監聽ws的關閉(bi)狀態
ws.onclose = function(event){ //關閉時的處理操作 } -
主動關閉ws連接
ws.close();
3. ws的使用(yong)示(shi)例
private mounted() {
let { id } = this.$route.query
if (id) {
this.id = id
}
this.connect()
}
private destroyed() {
if (this.ws) {
this.ws.close()
}
}
private connect() {
// 1. 創建websocket對象,參數為服務器websocket地址
let path = `${prefix}/ws/get_task_log?id=${this.id}`
this.ws = new WebSocket(`ws://${window.location.host}${path}`)
// 2.監聽websocket的狀態變化,接收的信息,關閉時的狀態
//監聽連接狀態的變化
this.ws.onopen = () => this.socketChange()
//監聽接收消息的情況
this.ws.onmessage = event => {
let strData = atob(event.data)
if (this.switchValue === 'on') {
this.codeValue += strData
}
}
//監聽關閉時的狀態變化
this.ws.onclose = () => this.socketChange()
}
socketChange() {
let state = this.ws.readyState
let val = this.statusArr.find(item => {
return item.state == state
})
//實時顯示狀態的變化
console.log(`當前的socket連接狀態是: ${val?.value}`)
}