做pc端网站新闻,新网站建设的工作,成品免费网站源码,企业网站建设系统使用原因#xff1a;用户网络环境较差#xff0c;之前使用ws总是出现断连重连#xff0c;导致数据总是不能实时更新#xff0c;所以更换为sse
npm install event-source-polyfill
createWebSocket#xff1a;创建sse连接
getWebSocketMsg#xff1a;接收sse消息 impo…使用原因用户网络环境较差之前使用ws总是出现断连重连导致数据总是不能实时更新所以更换为sse
npm install event-source-polyfill
createWebSocket创建sse连接
getWebSocketMsg接收sse消息 import { EventSourcePolyfill } from event-source-polyfill;import { getToken } from /utils/authclass webSocketClass {constructor(name) {this.localUrl http; //直连阿里云正式环境this.globalCallback null;this.createWebSocket(name);this.readyState 0;}createWebSocket(url) {var that this// 建立连接this.eventSource new EventSourcePolyfill(this.localUrl url,{// 设置重连时间heartbeatTimeout: 60 * 60 * 1000,// 添加tokenheaders: {Authorization: Bearer ${getToken()},},});this.eventSource.onopen (e) {console.log(已建立SSE连接~);};this.eventSource.onmessage (e) {const d JSON.parse(e.data);console.log(sse已接受到消息:, d);that.getWebSocketMsg(that.globalCallback);};this.eventSource.onerror (e) {console.log(SSE连接错误 e.readyState);if (e.readyState EventSource.CLOSED) {console.log(SSE连接关闭);} else if (this.eventSource.readyState EventSource.CONNECTING) {console.log(SSE正在重连);//重新设置tokenthis.eventSource.headers {Authorization: Bearer ${getToken()},};} else {console.log(error, e);}};}getWebSocketMsg(callback) {console.log(开始接收sse消息~,this.eventSource);this.eventSource.onmessage (ev) {callback callback(ev);};}close(){this.eventSource.close()console.log(SSE关闭 e.readyState);}
}
export default webSocketClass;使用方法 this.warningSSE new vueSSEUtil(/sse/warning/this.userId);this.warningSSE.getWebSocketMsg((evt) {const d JSON.parse(evt.data);d.warnCode this.code_to_value(d.warnCode);console.log(sse回调数据,d) });
一定要在页面退出关闭sse
this.warningSSE.close()