因公司突然要求做個機器人客戶端,需要與機器人對接,采用了WebSocket技術實現瀏覽器與服務端進行聯調, 前端以WebSocket協議格式發送數據到后台, 后台解析指令並將指令發送到機器人, 機器人的相關相應信息也通過后台使用WebSocket協議封裝數據傳輸給瀏覽器
1 created() { 2 this.initWebSocket() 3 }, 4 methods: { 5 // 初始化weosocket 6 initWebSocket() { 7 // ws地址 8 const wsuri = 'ws://192.168.20.73:3002/websocket/robot' 9 this.websock = new WebSocket(wsuri) // 這里面的this都指向vue 10 this.websock.onmessage = this.websocketonmessage 11 this.websock.onclose = this.websocketclose 12 this.websock.onopen = this.websocketopen 13 this.websock.onerror = this.websocketerror 14 }, 15 websocketopen() { // 連接建立之后執行send方法發送數據 16 console.log('WebSocket連接成功') 17 const actions = { 18 'ip': this.ip, 19 'port': this.port, 20 'operate': this.operate 21 } 22 console.log('發送參數', actions) 23 setTimeout(() => { 24 this.websocketsend(JSON.stringify(actions)) 25 }, 500) 26 }, 27 websocketonmessage(e) { // 數據接收 28 const redata = JSON.parse(e.data) 29 console.log('數據內容:{0}', redata) 30 }, 31 websocketsend(param) { // 數據發送 32 console.log('***數據發送**', param) 33 try { 34 console.log('*****************', this.websock.readyState) 35 this.websock.send(param) 36 } catch (err) { 37 console.log('error', err) 38 } 39 }, 40 websocketclose(e) { // 關閉 41 console.log('WebSocket連接關閉', e) 42 }, 43 websocketerror() { // 失敗 44 console.log('WebSocket連接失敗') 45 this.initWebSocket() // 連接建立失敗重連 46 } 47 }
復制粘貼即可使用
歡迎掃碼加群,一起討論,共同學習成長!