1. 创立 eventsource.js 文件(eventsource.js 的代码在最初面)
2. 引入
import {EventSourcePolyfill} from "@/utils/eventsource.js";
3. 调用
getPresentMsg(){
let _this = this;
let url = 'http://192.168.110.183:90'
this.source = new EventSourcePolyfill(
url + "/worship/memPresentRecord/presentMsg?type=0&memorialId="+this.memorial.id,
{
headers: {// Authorization: "Bearer" + getToken(),
"Content-Type": "text/event-stream;charset=UTF-8",
"Cache-Control": "no-cache",
Connection: "keep-alive",
},
// 重连工夫距离,单位:毫秒,默认 45000 毫秒,这里设置为 10 分钟
heartbeatTimeout: 10 * 60 * 1000,
}
);
this.source.onopen = () => {console.log(1, "NOTICE 建设连贯");
};
this.source.onmessage = (e) => {
// _this.scrollMessage = e.data;
let presentId =JSON.parse(e.data).presentId
if(presentId){
let obj=jipinList.find(item=>{return item.id ==presentId})
_this.toSacrifice(obj)
}
};
this.source.onerror = (e) => {if (e.readyState == EventSource.CLOSED) {console.log(3, "NOTICE 连贯敞开");
} else if (this.source.readyState == EventSource.CONNECTING) {console.log(4, "NOTICE 正在重连");
// 从新设置 header
// this.source.headers = {// Authorization: "Bearer" + getToken(),
// };
} else {console.log(5, e);
}
};
},
eventsource.js 的代码
/** @license
- eventsource.js
- Available under MIT License (MIT)
- https://github.com/Yaffle/EventSource/
*/
!function(e){“use strict”;var r,H=e.setTimeout,N=e.clearTimeout,j=e.XMLHttpRequest,o=e.XDomainRequest,t=e.ActiveXObject,n=e.EventSource,i=e.document,w=e.Promise,d=e.fetch,a=e.Response,h=e.TextDecoder,s=e.TextEncoder,p=e.AbortController;function c(){this.bitsNeeded=0,this.codePoint=0}”undefined”==typeof window||void 0===i||”readyState”in i||null!=i.body||(i.readyState=”loading”,window.addEventListener(“load”,function(e){i.readyState=”complete”},!1)),null==j&&null!=t&&(j=function(){return new t(“Microsoft.XMLHTTP”)}),null==Object.create&&(Object.create=function(e){function t(){}return t.prototype=e,new t}),Date.now||(Date.now=function(){return(new Date).getTime()}),null==p&&(r=d,d=function(e,t){var n=t.signal;return r(e,{headers:t.headers,credentials:t.credentials,cache:t.cache}).then(function(e){var t=e.body.getReader();return n._reader=t,n._aborted&&n._reader.cancel(),{status:e.status,statusText:e.statusText,headers:e.headers,body:{getReader:function(){return t}}}})},p=function(){this.signal={_reader:null,_aborted:!1},this.abort=function(){null!=this.signal._reader&&this.signal._reader.cancel(),this.signal._aborted=!0}}),c.prototype.decode=function(e){function t(e,t,n){if(1===n)return 128>>t<=e&&e<<t<=2047;if(2===n)return 2048>>t<=e&&e<<t<=55295||57344>>t<=e&&e<<t<=65535;if(3===n)return 65536>>t<=e&&e<<t<=1114111;throw new Error}function n(e,t){if(6===e)return 15<t>>6?3:31<t?2:1;if(12===e)return 15<t?3:2;if(18===e)return 3;throw new Error}for(var r=””,o=this.bitsNeeded,i=this.codePoint,a=0;a<e.length;a+=1){var s=e[a];0!==o&&(s<128||191<s||!t(i<<6|63&s,o-6,n(o,i)))&&(o=0,i=65533,r+=String.fromCharCode(i)),0===o?(i=0<=s&&s<=127?(o=0,s):192<=s&&s<=223?(o=6,31&s):224<=s&&s<=239?(o=12,15&s):240<=s&&s<=247?(o=18,7&s):(o=0,65533),0===o||t(i,o,n(o,i))||(o=0,i=65533)):(o-=6,i=i<<6|63&s),0===o&&(i<=65535?r+=String.fromCharCode(i):r=(r+=String.fromCharCode(55296+(i-65535-1>>10)))+String.fromCharCode(56320+(i-65535-1&1023)))}return this.bitsNeeded=o,this.codePoint=i,r};function u(){}null!=h&&null!=s&&function(){try{return”test”===(new h).decode((new s).encode(“test”),{stream:!0})}catch(e){}return!1}()||(h=c);function I(e){this.withCredentials=!1,this.readyState=0,this.status=0,this.statusText=””,this.responseText=””,this.onprogress=u,this.onload=u,this.onerror=u,this.onreadystatechange=u,this._contentType=””,this._xhr=e,this._sendTimeout=0,this._abort=u}function l(e){return e.replace(/[A-Z]/g,function(e){return String.fromCharCode(e.charCodeAt(0)+32)})}function f(e){for(var t=Object.create(null),n=e.split(“\r\n”),r=0;r<n.length;r+=1){var o=n[r].split(“: “),i=o.shift(),o=o.join(“: “);t[l(i)]=o}this._map=t}function P(){}function y(e){this._headers=e}function L(){}function M(){this._listeners=Object.create(null)}function b(e){H(function(){throw e},0)}function v(e){this.type=e,this.target=void 0}function $(e,t){v.call(this,e),this.data=t.data,this.lastEventId=t.lastEventId}function q(e,t){v.call(this,e),this.status=t.status,this.statusText=t.statusText,this.headers=t.headers}function F(e,t){v.call(this,e),this.error=t.error}I.prototype.open=function(e,t){this._abort(!0);var o=this,i=this._xhr,a=1,n=0,r=(this._abort=function(e){0!==o._sendTimeout&&(N(o._sendTimeout),o._sendTimeout=0),1!==a&&2!==a&&3!==a||(a=4,i.onload=u,i.onerror=u,i.onabort=u,i.onprogress=u,i.onreadystatechange=u,i.abort(),0!==n&&(N(n),n=0),e||(o.readyState=4,o.onabort(null),o.onreadystatechange())),a=0},function(){if(1===a){var t=0,n=””,r=void 0;if(“contentType”in i)t=200,n=”OK”,r=i.contentType;else try{t=i.status,n=i.statusText,r=i.getResponseHeader(“Content-Type”)}catch(e){n=””,r=void(t=0)}0!==t&&(a=2,o.readyState=2,o.status=t,o.statusText=n,o._contentType=r,o.onreadystatechange())}}),s=function(){if(r(),2===a||3===a){a=3;var e=””;try{e=i.responseText}catch(e){}o.readyState=3,o.responseText=e,o.onprogress()}},c=function(e,t){if(null!=t&&null!=t.preventDefault||(t={preventDefault:u}),s(),1===a||2===a||3===a){if(a=4,0!==n&&(N(n),n=0),o.readyState=4,”load”===e)o.onload(t);else if(“error”===e)o.onerror(t);else{if(“abort”!==e)throw new TypeError;o.onabort(t)}o.onreadystatechange()}},l=function(){n=H(function(){l()},500),3===i.readyState&&s()};”onload”in i&&(i.onload=function(e){c(“load”,e)}),”onerror”in i&&(i.onerror=function(e){c(“error”,e)}),”onabort”in i&&(i.onabort=function(e){c(“abort”,e)}),”onprogress”in i&&(i.onprogress=s),”onreadystatechange”in i&&(i.onreadystatechange=function(e){e=e,null!=i&&(4===i.readyState?”onload”in i&&”onerror”in i&&”onabort”in i||c(“”===i.responseText?”error”:”load”,e):3===i.readyState?”onprogress”in i||s():2===i.readyState&&r())}),!(“contentType”in i)&&”ontimeout”in j.prototype||(t+=(-1===t.indexOf(“?”)?”?”:”&”)+”padding=true”),i.open(e,t,!0),”readyState”in i&&(n=H(function(){l()},0))},I.prototype.abort=function(){this._abort(!1)},I.prototype.getResponseHeader=function(e){return this._contentType},I.prototype.setRequestHeader=function(e,t){var n=this._xhr;”setRequestHeader”in n&&n.setRequestHeader(e,t)},I.prototype.getAllResponseHeaders=function(){return null!=this._xhr.getAllResponseHeaders&&this._xhr.getAllResponseHeaders()||””},I.prototype.send=function(){var e;if(“ontimeout”in j.prototype&&(“sendAsBinary”in j.prototype||”mozAnon”in j.prototype)||null==i||null==i.readyState||”complete”===i.readyState){var t=this._xhr;”withCredentials”in t&&(t.withCredentials=this.withCredentials);try{t.send(void 0)}catch(e){throw e}}else(e=this)._sendTimeout=H(function(){e._sendTimeout=0,e.send()},4)},f.prototype.get=function(e){return this._map[l(e)]},null!=j&&null==j.HEADERS_RECEIVED&&(j.HEADERS_RECEIVED=2),P.prototype.open=function(o,i,t,n,e,r,a){o.open(“GET”,e);var s,c=0;for(s in o.onprogress=function(){var e=o.responseText.slice(c);c+=e.length,t(e)},o.onerror=function(e){e.preventDefault(),n(new Error(“NetworkError”))},o.onload=function(){n(null)},o.onabort=function(){n(null)},o.onreadystatechange=function(){var e,t,n,r;o.readyState===j.HEADERS_RECEIVED&&(e=o.status,t=o.statusText,n=o.getResponseHeader(“Content-Type”),r=o.getAllResponseHeaders(),i(e,t,n,new f(r)))},o.withCredentials=r,a)Object.prototype.hasOwnProperty.call(a,s)&&o.setRequestHeader(s,a[s]);return o.send(),o},y.prototype.get=function(e){return this._headers.get(e)},L.prototype.open=function(e,t,o,n,r,i,a){var s=null,c=new p,l=c.signal,u=new h;return d(r,{headers:a,credentials:i?”include”:”same-origin”,signal:l,cache:”no-store”}).then(function(e){return s=e.body.getReader(),t(e.status,e.statusText,e.headers.get(“Content-Type”),new y(e.headers)),new w(function(t,n){function r(){s.read().then(function(e){e.done?t(void 0):(e=u.decode(e.value,{stream:!0}),o(e),r())}).catch(function(e){n(e)})}r()})}).catch(function(e){if(“AbortError”!==e.name)return e}).then(function(e){n(e)}),{abort:function(){null!=s&&s.cancel(),c.abort()}}},M.prototype.dispatchEvent=function(e){var t=(e.target=this)._listeners[e.type];if(null!=t)for(var n=t.length,r=0;r<n;r+=1){var o=t[r];try{“function”==typeof o.handleEvent?o.handleEvent(e):o.call(this,e)}catch(e){b(e)}}},M.prototype.addEventListener=function(e,t){e=String(e);for(var n=this._listeners,r=n[e],o=(null==r&&(n[e]=r=[]),!1),i=0;i<r.length;i+=1)r[i]===t&&(o=!0);o||r.push(t)},M.prototype.removeEventListener=function(e,t){e=String(e);var n=this._listeners,r=n[e];if(null!=r){for(var o=[],i=0;i<r.length;i+=1)r[i]!==t&&o.push(r[i]);0===o.length?delete n[e]:n[e]=o}},$.prototype=Object.create(v.prototype),q.prototype=Object.create(v.prototype),F.prototype=Object.create(v.prototype);var X=-1,G=0,V=1,B=2,k=-1,z=0,K=1,J=2,W=3,Y=/^text/event-stream(;.)?$/i,E=1e3,m=18e6,Q=function(e,t){e=null==e?t:parseInt(e,10);return U(e=e!=e?t:e)},U=function(e){return Math.min(Math.max(e,E),m)},Z=function(e,t,n){try{“function”==typeof t&&t.call(e,n)}catch(e){b(e)}};function g(e,t){function i(e,t,n,r){var o;m===G&&(200===e&&null!=n&&Y.test(n)?(m=V,y=Date.now(),f=d,c.readyState=V,o=new q(“open”,{status:e,statusText:t,headers:r}),c.dispatchEvent(o),Z(c,c.onopen,o)):(200!==e?t=t&&t.replace(/\s+/g,” “):null!=n&&n.replace(/\s+/g,” “),O(),o=new q(“error”,{status:e,statusText:t,headers:r}),c.dispatchEvent(o),Z(c,c.onerror,o)))}function a(e){if(m===V){for(var t=-1,n=0;n<e.length;n+=1)(a=e.charCodeAt(n))!==”\n”.charCodeAt(0)&&a!==”\r”.charCodeAt(0)||(t=n);var r=(-1!==t?S:””)+e.slice(0,t+1);S=(-1===t?S:””)+e.slice(t+1),””!==e&&(y=Date.now(),v+=e.length);for(var o=0;o<r.length;o+=1){var i,a=r.charCodeAt(o);if(x===k&&a===”\n”.charCodeAt(0))x=z;else if(x===k&&(x=z),a===”\r”.charCodeAt(0)||a===”\n”.charCodeAt(0)){if(x!==z&&(x===K&&(R=o+1),s=r.slice(A,R-1),i=r.slice(R+(R<o&&r.charCodeAt(R)===” “.charCodeAt(0)?1:0),o),”data”===s?C=C+”\n”+i:”id”===s?T=i:”event”===s?_=i:”retry”===s?(d=Q(i,d),f=d):”heartbeatTimeout”===s&&(h=Q(i,h),0!==E&&(N(E),E=H(function(){D()},h)))),x===z){if(“”!==C){p=T;var s=new $(_=””===_?”message”:_,{data:C.slice(1),lastEventId:T});if(c.dispatchEvent(s),”open”===_?Z(c,c.onopen,s):”message”===_?Z(c,c.onmessage,s):”error”===_&&Z(c,c.onerror,s),m===B)return}_=C=””}x=a===”\r”.charCodeAt(0)?k:z}else x===z&&(A=o,x=K),x===K?a===”:”.charCodeAt(0)&&(R=o+1,x=J):x===J&&(x=W)}}}function s(e){m!==V&&m!==G||(m=X,0!==E&&(N(E),E=0),E=H(function(){D()},f),f=U(Math.min(16d,2f)),c.readyState=G,e=new F(“error”,{error:e}),c.dispatchEvent(e),Z(c,c.onerror,e))}var c,l,u,d,h,p,f,y,v,n,g,w,b,E,m,C,T,_,S,x,A,R,O,D;M.call(this),t=t||{},this.onopen=void 0,this.onmessage=void 0,this.onerror=void 0,this.url=void 0,this.readyState=void 0,this.withCredentials=void 0,this.headers=void 0,this._close=void 0,c=this,l=e,e=t,l=String(l),t=Boolean(e.withCredentials),u=e.lastEventIdQueryParameterName||”lastEventId”,d=U(1e3),h=Q(e.heartbeatTimeout,45e3),p=””,f=d,y=!1,v=0,n=e.headers||{},e=e.Transport,g=ee&&null==e?void 0:new I(new(null!=e?e:null!=j&&”withCredentials”in j.prototype||null==o?j:o)),w=new(null!=e&&”string”!=typeof e?e:null==g?L:P),b=void 0,m=X,S=_=T=C=””,x=z,R=A=E=0,O=function(){m=B,null!=b&&(b.abort(),b=void 0),0!==E&&(N(E),E=0),c.readyState=B},D=function(){if(E=0,m!==X)y||null==b?(e=Math.max((y||Date.now())+h-Date.now(),1),y=!1,E=H(function(){D()},e)):(s(new Error(“No activity within “+h+” milliseconds. “+(m===G?”No response received.”:v+” chars received.”)+” Reconnecting.”)),null!=b&&(b.abort(),b=void 0));else{y=!1,v=0,E=H(function(){D()},h),m=G,T=p,S=_=C=””,R=A=0,x=z;var e=l,t=(“data:”!==l.slice(0,5)&&”blob:”!==l.slice(0,5)&&””!==p&&(e=-1===(t=l.indexOf(“?”))?l:l.slice(0,t+1)+l.slice(t+1).replace(/(?:^|&)(1)(?:=2*)?/g,function(e,t){return t===u?””:e}),e+=(-1===l.indexOf(“?”)?”?”:”&”)+u+”=”+encodeURIComponent(p)),c.withCredentials),n={Accept:”text/event-stream”},r=c.headers;if(null!=r)for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[o]=r[o]);try{b=w.open(g,i,a,s,e,t,n)}catch(e){throw O(),e}}},c.url=l,c.readyState=G,c.withCredentials=t,c.headers=n,c._close=O,D()}var ee=null!=d&&null!=a&&”body”in a.prototype;(g.prototype=Object.create(M.prototype)).CONNECTING=G,g.prototype.OPEN=V,g.prototype.CLOSED=B,g.prototype.close=function(){this._close()},g.CONNECTING=G,g.OPEN=V,g.CLOSED=B,g.prototype.withCredentials=void 0;var C=n;null==j||null!=n&&”withCredentials”in n.prototype||(C=g),a=function(e){e.EventSourcePolyfill=g,e.NativeEventSource=n,e.EventSource=C},”object”==typeof module&&”object”==typeof module.exports?a(exports):”function”==typeof define&&define.amd?define([“exports”],a):a(e)}(“undefined”==typeof globalThis?”undefined”!=typeof window?window:”undefined”!=typeof self?self:this:globalThis);
- =& ↩
- & ↩