Vue+WebSocket实现客户端与服务端通讯,前端与机器人对接

 因公司突然要求做个机器人客户端,需要与机器人对接,采用了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   }

 

 

复制粘贴即可使用

 

                

 

   欢迎扫码加群,一起讨论,共同学习成长!

posted @ 2020-04-03 11:12  此夏_唯美  阅读(2127)  评论(1编辑  收藏  举报