webSocket
服务端可以主动向客户端推送消息,客户端也可以向服务端发送请求。没有同源限制,客户端可以与任意服务器去通信。
在组件加载的时候连接websocket,在组建销毁的时候断开webSocket。后端接口也需要引入socket模块,否则不能实现连接。
1)初始化
首先判断浏览器是否支持webSocket的方法。
if(typeof(WebSocket) === "undefined") {
this.msgError('您的浏览器不支持WebSocket,请升级浏览器版本后,再重试。')
} else {
// 支持情况下,编写接下来相应的代码
this.webSockt = new WebSocket(wsUrl, getToken()) //实例化socket
this.webSockt.onopen = this.onOpen //链接建立之后执行send方法发送数据。
this.webSockt.onerror = this.onError //链接建立失败重连。
this.webSockt.onmessage = this.getMessage //数据接收
this.webSockt.onclose = this.onClose //关闭,断开连接。
}
2)监听销毁
beforeDestroy() {
this.webSockt && this.webSockt.close()
}