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

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

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

当我们使用微信小程序对接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封装的原生Ajax请求

Javascript封装的原生Ajax请求

由于工作需要长期使用Ajax,一个页面重复的AJAX请求太多,于是封装起来,只需要编写回调函数/* ------------- 使用方法: 1.ajaxrequest()函数执行准备的参数(1.请求地址2.发送数据字符串拼接3.type值可选get/post4.回调函数名称)   exam...

阻止表单提交刷新页面

阻止表单提交刷新页面

<form action="save.php" method="post"   target="nm_iframe">      &nbs...

websql的使用方法

websql的使用方法

<!--          三个核心方法          openDatabase:这个方法使用现有数据库或创建...

canvs转图片canvs转base64

canvs转图片canvs转base64

二期项目中生成的简历二维码是使用canvs生成的,微信浏览器中不能识别二维码,只能扫码。懒的换phpqrcode,于是转canvs。//设置一个url var url = "{yun:}$config.sy_weburl{/yun}/mingli/index....

 js构造函数

js构造函数

工厂模式虽然解决了创建多个对象的问题,但是并没有解决识别对象从属的问题.因为都属于object.因此出现了构造函数//构造函数名称首字母大写是规范 function Box(name,age){ this.name=name; this.age=age; this.run=funct...

js Promise对象,js then catch

js Promise对象,js then catch

具体文章解释请看廖雪峰老师的文章,这里仅仅记录笔记。国内飞机票点击访问首次接触可能一脸懵逼,下面的代码手把手敲一遍,100%懂。(1).基础demo//创建承诺 let p1 = new Promise(function (resolve, ...