赞
踩
效果如下:
SSE问题太多,所以还是配合websorket实现
1.连接sorket
const handleConnectWebScoket = (session_id:Number) => { uni.showLoading({ title: '加载中' }) uni.connectSocket({ url: '' //后端url , success(data) { console.log("websocket连接成功"); }, }) uni.onSocketOpen(function (res_open) { console.log("websocket - onSocketOpen"); sendWSMessage(session_id) receiveSocketMessage() }) // 监听webSocket错误 uni.onSocketError(function (res) { console.log("websocket监控服务暂时不可用", res); }) }
2.发布sorket的message
const sendWSMessage = (session_id:Number) => {
let form = { // 后端定义的传参
params: {
}
}
console.log("websocket - sendSocketMessage");
uni.sendSocketMessage({
data: JSON.stringify(form),
success: res => {
}
});
}
3.获取sorket的内容
const receiveSocketMessage = () => { console.log("websocket - onSocketMessage"); uni.onSocketMessage(function(res) { uni.hideLoading() if (res.data === 'PONG') { return } if (res.data && isJSON(res.data)) { const data = JSON.parse(res.data) if (data.code && data.code === 4002) { if (interval.value){ clearInterval(interval.value) } closeWS() return } if (data.content) { if (isJSON(data.content)) { const content = JSON.parse(data.content) if (content.choices[0].delta.content) { list.value[index.value] += content.choices[0].delta.content chatScroll() } } if (data.content === '\\n\\n') { list.value[index.value] += data.content } } } }) }
关闭sorket的方法
const closeWS = () => {
uni.closeSocket({
success(close_res) {
console.log('close_res',close_res);
},fail(e) {
console.log('close_fail',e)
}
})
}
如何使用呢?
const index = ref<number>(0)
const list = ref<Array<string>>([])
页面如何展示
{{ list[index] }}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。