分享一个让 uniapp 微信小程序支持 EventSource 的方法
微信小程序不支持
EventSource(SSE)是一种HTML5标准,旨在提供一种方式来在Web应用中实现异步通信和事件处理。
然而,根据现有的信息,uni-app并没有直接支持EventSource,这意味着开发者需要寻找其他技术或替代方案来实现类似的效果。
尽管有些主流浏览器支持SSE,但小程序目前还不能兼容这个API,这可能是由于微信平台对新技术的兼容性考虑或是开发生态的限制。
一个替代实现方式
class EventSource {
constructor(url, retryTime = 0) {
this.url = url;
this.retryTime = retryTime;
this.listeners = {};
this.requestTask = null
this.connect()
}
connect() {
this.requestTask = wx.request({
url: this.url,
enableChunked: true,
responseType: 'text',
method: 'GET',
timeout: 300e3,
success: res => {
this.emit('success', res)
if (this.retryTime > 0) {
setTimeout(() => {
this.connect()
}, this.retryTime)
}
},
fail: () => {
}
});
this.requestTask.onHeadersReceived(res => {
this.emit('open', res);
})
this.requestTask.onChunkReceived(res => this.handleChunk(res))
}
handleChunk(res) {
const arrayBuffer = res.data;
const uint8Array = new Uint8Array(arrayBuffer);
let data = uni.arrayBufferToBase64(uint8Array)
data = new Buffer(data, 'base64')
data = data.toString('utf8')
const lines = data.split("\n\n")
// console.log('data', data, lines)
lines.forEach(line => {
if (!line.trim()) {
return
}
const [key, value] = line.trim().split(':');
if (key === 'data') {
const data = line.substring(5).trim();
try {
const json = JSON.parse(data);
this.emit('message', {
data: JSON.stringify(json)
})
} catch (e) {
this.emit('error', 'Api.EventSource.ParseError:' + e)
}
} else {
this.emit('error', 'Api.EventSource.ParseFail:' + line)
}
})
}
addEventListener(event, callback) {
if (!this.listeners[event]) {
this.listeners[event] = []
}
this.listeners[event].push(callback)
}
emit(event, data) {
if (this.listeners[event]) {
this.listeners[event].forEach(callback => {
callback(data)
});
}
}
close() {
if (this.requestTask) {
this.requestTask.abort()
}
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
:+1: