Websocket在Vue中的使⽤
1、初始化WebSocket对象
为了兼容各个浏览器所以初始化的时候针对不同的浏览器初始化调⽤不同的⽅法。
2、注册Websocket的url
websocket和socket
其中CONFIG.WEBSOCKET_URL为wensocket服务地址,_this.userData.user是登录⽤户的⽤户名,这样做为了保证不同⽤户的websocket 地址的唯⼀性,防⽌消息发⽣混淆。
3、增加⼼跳检测
由于⽹络以及websocket⾃⾝的⼀些不稳定性,页⾯长时间打开的情况下有时会发⽣websocket链接的断开,为了防⽌这种情况,我们增加⼼跳检测机制
并且在websocket链接建⽴时触发该⽅法
4、Vue组件中什么时候创建和销毁websocket对象
为了保证websocket对象能够及时创建,建议在vue的created的钩⼦函数中触发websocket的初始化,同时在beforeRouteLeave⽅法⾥关闭websocket的链接
5、完整代码参考
截图:
截图
源码(复制粘贴即可使⽤):
export default { name: 'Resource', data () { return { wsUrl: '', websocket:null } }, methods: { updateUrl(urlPath) { let _this = this; if (urlPath.indexOf('sockjs') != -1) { _this.wsUrl = '' + CONFIG.WEBSOCKET_URL + urlPath + ";" + _this.userData.user; } else { if (window.location.protocol
== 'http:') { _this.wsUrl = 'ws://' + CONFIG.WEBSOCKET_URL + urlPath + ";" + _this.userData.user; } else { _this.wsUrl = 'wss://' +
CONFIG.WEBSOCKET_URL + urlPath + ";" + _this.userData.user; } } }, webSocketLink(){ let _this = this; var heartCheck = { timeout: 5000,//5秒 timeoutObj: null, reset: function(){ clearInterval(this.timeoutObj); return this; }, start: function(){ this.timeoutObj = setInterval(function(){ _this.websocket.send("HeartBeat");
console.log("HeartBeat"); }, this.timeout) } }; if ('WebSocket' in window) {
_this.updateUrl("/webSocketServer"); _this.websocket = new WebSocket(_this.wsUrl); } else if
('MozWebSocket' in window) { _this.updateUrl("/webSocketServer"); _this.websocket = new
MozWebSocket(_this.wsUrl); } else { _this.updateUrl("/sockjs/webSocketServer"); _this.websocket = new SockJS(_this.wsUrl) } _pen = function(){ console.log("websock连接成功");
this.webSocketLink(); }}</script>