什么是WebSocket?
HTML5 WebSocket
WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。
WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
在 WebSocket API 中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。
现在,很多网站为了实现推送技术,所用的技术都是 Ajax 轮询。轮询是在特定的的时间间隔(如每1秒),由浏览器对服务器发出HTTP请求,然后由服务器返回最新的数据给客户端的浏览器。这种传统的模式带来很明显的缺点,即浏览器需要不断的向服务器发出请求,然而HTTP请求可能包含较长的头部,其中真正有效的数据可能只是很小的一部分,显然这样会浪费很多的带宽等资源。
原生使用方法
https://www.runoob.com/html/html5-websocket.html
vue 怎么使用WebSocket连接(这里使用组件)
// npm install --save reconnecting-websocket
import ReconnectingWebSocket from 'reconnecting-websocket';
vue页面注销时要关闭链接
// 页面注销时候调用 避免连接错误
destroyed() {
this.closeWebSocket();
},
创建WebSocket
mounted() {
// 创建 websocket 链接
this. createWebsocket();
},
methods: {
// 创建 websocket 链接
createWebsocket() {
const httpURL = process.env.VUE_APP_DOMAIN;
this.websocket = new ReconnectingWebSocket(`wss://${httpURL}custom_api/websocket/queue/${this.coding}`);
// 连接发生错误的回调方法
this.websocket.onerror = this.websocketOnerror;
// 连接成功建立的回调方法
this.websocket.onopen = this.websocketOnopen;
// 接收到消息的回调方法
this.websocket.onmessage = this.websocketOnmessage;
// 连接关闭的回调方法
this.websocket.onclose = this.websocketOnclose;
// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
this.websocket.onbeforeunload = this.websocketOnbeforeunload;
},
// 连接发生错误的回调方法
websocketOnerror() {
console.log('连接发生错误的回调方法');
},
// 连接成功建立的回调方法
websocketOnopen() {
console.log('连接成功建立的回调方法');
},
// 接收到消息的回调方法
websocketOnmessage(event) {
const data = JSON.parse(event.data);
console.log('接收到消息的回调方法', data);
},
// 连接关闭的回调方法
websocketOnclose() {
console.log('连接关闭的回调方法');
},
// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常
websocketOnbeforeunload() {
this.closeWebSocket();
console.log('监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常');
},
// 关闭WebSocket连接
closeWebSocket() {
this.websocket.close();
},
}