1、需求背景
工程車巡檢,實時發送巡檢位置信息、現場狀況到服務器,頁面實時顯示工程車位置以及狀況信息
2、VUE中使用socket建立實時連接
3、mounted生命周期中初始化連接
mounted () {this.initWebSocket() },
4、socket連接方法
/** * 建立socket連接,調用時間: * 1.首次進入頁面,如果不是查看記錄,請求出來初始數據后,建立socket連接 * 2.調用數據庫查詢完畢后 * */ initWebSocket() { //初始化weosocket const wsuri = 'ws://121.40.165.18:8800/' this.websock = new WebSocket(wsuri) this.websock.onmessage = this.websocketonmessage this.websock.onopen = this.websocketonopen this.websock.onerror = this.websocketonerror this.websock.onclose = this.websocketclose }, websocketonopen() { //連接建立之后執行send方法發送數據 let actions = {'tags': ['ypt/leak/textplantrecord/getlist'],'machineid':'18279'} this.websocketsend(JSON.stringify(actions)) }, /** * 連接建立失敗,斷開連接 * 1.查詢一次數據庫數據 * 2.查詢完后再次建立socket連接 * */ websocketonerror() {//連接建立失敗重連 let _this = this console.log('連接建立失敗') //this.websock.onclose() this.initWebSocket() }, websocketonmessage(e) { //數據接收 //const redata = JSON.parse(e.data) console.log(e.data) this.dealF2DataList(redata) }, websocketsend(Data) {//數據發送 this.websock.send(Data) }, websocketclose(e) { //關閉 console.log('斷開連接', e) },
5、連接狀態
6、數據輸出(在websocketonmessage里調用數據處理方法)
7、WebSocket 在線測試(點擊跳轉)