这段时间使用了一下websoket,抽出时间做个记录和总结
注:js自带websoket,不需要引入
本方法,通过按键触发,事件写在methods的方法中,通过按钮以及destroyed周期来关闭
websocket的建立以及使用,JS(方法内代码,自定义方法包裹一下代码即可)如下
let that = this
let wsuri = 'ws//192.168.1.1:8080:/baidu' // 设置要访问的websoket路径
that.websock = new WebSocket(wsuri)
that.websock.onmessage = function(e) {
console.log(e) // 打印后端返回的参数,方法也写在这里
}
that.websock.onopen = function () {
console.log('建立连接') // 连接建立成功后的提示
that.websock.send("发送数据"); // 用于发送给后台验证或调用的数据
}
that.websock.onerror = function () {
that.initWebSocket() // 用于断开时的重连
}
that.websock.onclose = function () {
console.log('断开连接') // 断开连接的时候打印,用于提示
}
断开连接的方法(可以改为方法,在需要断开和销毁组件的时候调用,本方法为销毁组件时调用)
destroyed () {
if (this.websock) { // 判断websockt连接对象有没有创建
if (this.websock.readyState == 1) { // 判断是否处于连接状态
this.websock.close() // 断开websockt连接
}
}
}