下面是自己写的demo和注释,为了以后再用websocket,看起来方便一点=-=
<template>
<div>
<button @click="sendDevName('xxxxxxxx')">发送</button>
{{data}}
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
data: null
}
},
// html加载完成后执行initWebSocket()进行websocket初始化
mounted () {
this.initWebSocket()
},
// 离开该层时执行,划重点了!!!
destroyed: function () {
// 离开路由之后断开websocket连接
this.websock.close()
},
methods: {
// 初始化websocket
initWebSocket () {
const path = 'ws://xxx.xxx.xxx.xxx:端口号/xxxxx'// 后台给的websocket的ip地址
this.websock = new WebSocket(path)
this.websock.onmessage = this.websocketOnMessage
this.websock.onopen = this.websocketOnOpen
this.websock.onerror = this.websocketOnError
this.websock.onclose = this.websocketClose
},
// 连接建立成功的信号
websocketOnOpen () {
console.log('初始化成功')// 连接成功后就可以在这里写一些回调函数了
},
// 连接建立失败重连
websocketOnError () {
// 如果报错的话,在这里就可以重新初始化websocket,这就是断线重连
this.initWebSocket()
},
// 数据接收
websocketOnMessage (e) {
console.log(e)// e这个变量就是后台传回的数据,在这个函数里面可以进行处理传回的值
this.data = e// 这边我绑定了一个data,data会在网页上显示后端传来的东西
},
// 数据发送
websocketSend (Data) {
this.websock.send(Data)// Data变量就是你想对后台说些啥,根据后端给你的接口文档传值进行交互
},
// 关闭的信号
websocketClose () {
console.log('断开连接')
},
// 传参给后端,这里对websocketSend又进行了一层封装,用不到的可以删除
sendDevName (chooseDevice) {
console.log(chooseDevice)
this.websocketSend(chooseDevice)
}
}
}
</script>
前端点击发送
后端服务器就会接受到马赛克里面的东西
前端点击发送按钮触发websocketSend (Data)函数后端就会收到前端发的消息,根据前端传过来的消息再发送前端所需要的信息,前端一旦监听到有东西发过来就会触发websocketOnMessage (e)这个函数
编写代码时我踩的坑
Uncaught InvalidStateError: Failed to execute ‘send’ on ‘WebSocket’: Still in CONNECTING state
这个意思是说,websocket还在连接状态,调用send方法失败
原因是我在初始化websocket时,我就直接调用send给后台喊话了,这个时候websocket可能还没连接上去,就会报这个错误
所以我学乖了,在初始化成功过后我再喊话,就不会有问题
普及一下websocket的状态
websocket的两个属性:readyState和bufferedAmount。
根据readyState属性可以判断webSocket的连接状态,该属性的值可以是下面几种:
0 :对应常量CONNECTING (numeric value 0),
正在建立连接连接,还没有完成。The connection has not yet been established.
1 :对应常量OPEN (numeric value 1),
连接成功建立,可以进行通信。The WebSocket connection is established and communication is possible.
2 :对应常量CLOSING (numeric value 2)
连接正在进行关闭握手,即将关闭。The connection is going through the closing handshake.
3 : 对应常量CLOSED (numeric value 3)
连接已经关闭或者根本没有建立。The connection has been closed or could not be opened.
例:
var socket = new WebSocket(url);
if(socket.readyState!=1){
alert(“未连接。”);
return;
}
根据bufferedAmount可以知道有多少字节的数据等待发送,若websocket已经调用了close方法则该属性将一直增长。