当前位置:首页 > H5 > 正文内容

微信小程序不支持EventSource的解决方案

高老师2年前 (2024-05-19)H5882

当我们使用微信小程序对接ai功能时一般都需要打字机效果,一般ai接口都是sse协议,但是微信小程序不支持,垃圾东西,阉割了h5标准功能。我们需要给微信小程序模拟支持下。代码如下:

类库如下:

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) {
		console.log('ok');
        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")
        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
                    })
                } 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()
        }
    }
}

module.exports = EventSource;

调用方式参考例子:

const es = new EventSource('http://api.20230611.cn/api/question/aiExplanation?id=' + item.id)
es.addEventListener('open', res => {
	that.showAiExplanation = status;
});
es.addEventListener('message', (event) => {
	console.log('message');
});

虽然支持了微信小程序,但是uniapp是基于webview实现,webview中不支持EventSource,太折腾了所以放弃了sse作为多平台协议的支持,还是websocket支持比较多。

扫描二维码推送至手机访问。

版权声明:本文由高久峰个人博客发布,如需转载请注明出处。

本文链接:https://blog.20230611.cn/post/764.html

分享给朋友:

“微信小程序不支持EventSource的解决方案” 的相关文章

Javascript事件冒泡和捕捉的阻止

Javascript事件冒泡和捕捉的阻止

<!DOCTYPE html> <html> <head> <title>捕捉和冒泡</title> <meta charset="utf-8"> </head> <bo...

 js图片旋转插件jqueryrotate

js图片旋转插件jqueryrotate

jQuery 插件——jqueryrotate,它可以实现旋转效果。jqueryrotate 支持所有主流浏览器,包括 IE6。如果提示方法不存在,可能是你的Jquery版本过低或者过高。基本语法:$('#img').rotate(90);//旋转90度其他的参数:参数类型说明默认值...

es6模板字符串

es6模板字符串

在es5的时候变量只能通过+号拼接,es6种允许将变量放在大括号之中。有点类似php和c#对字符串的操作。    <script type="text/javascript">    &n...

js箭头函数,es6箭头函数

js箭头函数,es6箭头函数

基本结构:箭头函数左边是参数,右边是返回值//创建func函数let func = num => num;//上面的func函数等价于let oldFunc = function (num) {...

js生成二维码,JavaScript 生成二维码

js生成二维码,JavaScript 生成二维码

js生成二维码(1).下载二维码类库https://github.com/davidshimjs/qrcodejs(2).引入类库<script type="text/javascript" src="//static.runoob.com/a...

css多个选择器用同一种样式,CSS多个选择器共用一个样式

css多个选择器用同一种样式,CSS多个选择器共用一个样式

只需要每个选择器之间用,隔开.class_a , .class_b{     text-decoration: none;     color: #474747; }这东西都能忘记...