# uni.connectEventSource(options)

连接 SSE GitCode GitHub

SSE,全称是Server-sent Events,一种服务器基于http向客户端推送文本消息的技术。

一些AI大语言模型的服务器,利用SSE向客户端不停的发消息,持续的流式输出AI推理的结果文本。

# connectEventSource 兼容性

Web 微信小程序 Android Android uni-app x UTS 插件 iOS iOS uni-app x UTS 插件 HarmonyOS
x - 4.51 4.51 4.63 4.63 x

Web端暂未兼容uni.connectEventSource API,请使用标准的Web API。

小程序不直接支持SSE,替代方案有3种:

  1. 使用web-view组件,调用浏览器的SSE能力
  2. 使用socket。 如果是搭建自己的服务器对接AI服务器,可以由自己的服务器使用SSE连接AI服务器,然后转socket和客户端通信。 socket在跨端、双向传输、二进制传输上有更多优势。
  3. 使用request的Chunk,开启arraybuffer,可以流式接受数据,再通过三方库的TextEncoder解码出文本。

# 参数

名称 类型 必填 默认值 兼容性 描述
options ConnectEventSourceOptions - -
名称 类型 必备 默认值 兼容性 描述
url string -
服务器地址
header UTSJSONObject -
请求头

# 返回值

类型
UniEventSource

# UniEventSource 的方法

# onMessage(callback : ConnectEventSourceCallback) : void

message 事件,会在通过事件源收到数据时触发。

# onMessage 兼容性
Web 微信小程序 Android Android uni-app x UTS 插件 iOS iOS uni-app x UTS 插件 HarmonyOS
x - 4.51 4.51 4.63 4.63 x
# 参数
名称 类型 必填 默认值 兼容性 描述
callback (ev: UniMessageEvent) => void - - 事件回调
# UniMessageEvent 的属性值
名称 类型 必备 默认值 兼容性 描述
type string null
事件类型。
data any null
消息发射器发出的数据。
lastEventId string null
一个字符串,表示事件的唯一 ID。

# onError(callback : ConnectEventSourceErrorCallback) : void

onerror 是当发生错误且这个错误事件(error)被 UniEventSource 触发时调用的一个事件处理函数。

# onError 兼容性
Web 微信小程序 Android Android uni-app x UTS 插件 iOS iOS uni-app x UTS 插件 HarmonyOS
x - 4.51 4.51 4.63 4.63 x
# 参数
名称 类型 必填 默认值 兼容性 描述
callback (error: UniError) => void - - 事件回调

# onOpen(callback : ConnectEventSourceCallback) : void

一个事件处理器,它在收到 open 事件时被调用,在那时,连接刚被打开。

# onOpen 兼容性
Web 微信小程序 Android Android uni-app x UTS 插件 iOS iOS uni-app x UTS 插件 HarmonyOS
x - 4.51 4.51 4.63 4.63 x
# 参数
名称 类型 必填 默认值 兼容性 描述
callback (ev: UniMessageEvent) => void - - 事件回调

# close() : void

关闭当前的连接

# close 兼容性
Web 微信小程序 Android Android uni-app x UTS 插件 iOS iOS uni-app x UTS 插件 HarmonyOS
x - 4.51 4.51 4.63 4.63 x

# 示例

hello uni-app x

该 API 不支持 Web,请运行 hello uni-app x 到 App 平台体验

扫码体验(手机浏览器跳转到App直达页)
<template>

  <page-head :title="title"></page-head>
	<button class="button" type="primary" @click="connect">连接</button>
	<button class="button" type="primary" @click="close">关闭</button>

	<!-- #ifdef APP -->
	<scroll-view style="flex:1">
	<!-- #endif -->
		<view>
			<text style="width: 100%; text-align: center; margin-bottom: 5px;">
			  显示简易操作日志(可滚动查看)
			</text>
			<button size="mini" @click="logList = []">清空日志</button>
			<view style="margin-top: 10px;">
				<view v-for="(item, index) in logList" :key="index">
					<text style="margin-left: 20px; margin-right: 20px;">
						{{ item }}
					</text>
				</view>
			</view>
		</view>
	<!-- #ifdef APP -->
	</scroll-view>
	<!-- #endif -->
</template>

<script>
	export default {
		data() {
			return {
				logList: [] as string[],
				title: 'sse',
				url: 'https://request.dcloud.net.cn/api/sse/connect',
				eventSource: null as UniEventSource | null,
				open: false,
				receiveMessage: false
			}
		},
		unmounted() {
			if (this.eventSource != null) {
				this.eventSource?.close()
			}
		},
		methods: {
			connect() {
				console.log('connect start')
				uni.showLoading({
					title: "",
					mask: true
				})
				this.eventSource?.close()
				let headers : UTSJSONObject = new UTSJSONObject()
				headers.set("header1", "value1")
				headers.set("header2", "value3")
				this.eventSource = uni.connectEventSource({
					url: this.url,
					header: headers
				})
				this.eventSource?.onMessage((ev) => {
					const log = 'onMessage callback:' + '\n' + 'type: ' + ev.type + '\n' + 'data: ' + ev.data + '\n\n'
					this.logList.push(log)
					this.receiveMessage = true
					uni.hideLoading()
				})
				this.eventSource?.onOpen((ev) => {
					const log = 'onOpen callback: ' + ev.type + '\n\n'
					this.logList.push(log)
					this.open = true
				})
				this.eventSource?.onError((err) => {
          const log = `onError callback: ${err} \n\n`
					this.logList.push(log)
					uni.hideLoading()
				})
			},
			close() {
				this.eventSource?.close()
				const log = 'connect close' + '\n\n'
				this.logList.push(log)
			}
		}
	}
</script>

<style>
	.button {
		margin-left: 30px;
		margin-right: 30px;
		margin-bottom: 15px;
	}
</style>

# 参见

# 示例

hello uni-app x

该 API 不支持 Web,请运行 hello uni-app x 到 App 平台体验

扫码体验(手机浏览器跳转到App直达页)
<template>

  <page-head :title="title"></page-head>
	<button class="button" type="primary" @click="connect">连接</button>
	<button class="button" type="primary" @click="close">关闭</button>

	<!-- #ifdef APP -->
	<scroll-view style="flex:1">
	<!-- #endif -->
		<view>
			<text style="width: 100%; text-align: center; margin-bottom: 5px;">
			  显示简易操作日志(可滚动查看)
			</text>
			<button size="mini" @click="logList = []">清空日志</button>
			<view style="margin-top: 10px;">
				<view v-for="(item, index) in logList" :key="index">
					<text style="margin-left: 20px; margin-right: 20px;">
						{{ item }}
					</text>
				</view>
			</view>
		</view>
	<!-- #ifdef APP -->
	</scroll-view>
	<!-- #endif -->
</template>

<script>
	export default {
		data() {
			return {
				logList: [] as string[],
				title: 'sse',
				url: 'https://request.dcloud.net.cn/api/sse/connect',
				eventSource: null as UniEventSource | null,
				open: false,
				receiveMessage: false
			}
		},
		unmounted() {
			if (this.eventSource != null) {
				this.eventSource?.close()
			}
		},
		methods: {
			connect() {
				console.log('connect start')
				uni.showLoading({
					title: "",
					mask: true
				})
				this.eventSource?.close()
				let headers : UTSJSONObject = new UTSJSONObject()
				headers.set("header1", "value1")
				headers.set("header2", "value3")
				this.eventSource = uni.connectEventSource({
					url: this.url,
					header: headers
				})
				this.eventSource?.onMessage((ev) => {
					const log = 'onMessage callback:' + '\n' + 'type: ' + ev.type + '\n' + 'data: ' + ev.data + '\n\n'
					this.logList.push(log)
					this.receiveMessage = true
					uni.hideLoading()
				})
				this.eventSource?.onOpen((ev) => {
					const log = 'onOpen callback: ' + ev.type + '\n\n'
					this.logList.push(log)
					this.open = true
				})
				this.eventSource?.onError((err) => {
          const log = `onError callback: ${err} \n\n`
					this.logList.push(log)
					uni.hideLoading()
				})
			},
			close() {
				this.eventSource?.close()
				const log = 'connect close' + '\n\n'
				this.logList.push(log)
			}
		}
	}
</script>

<style>
	.button {
		margin-left: 30px;
		margin-right: 30px;
		margin-bottom: 15px;
	}
</style>

# 通用类型

# GeneralCallbackResult

名称 类型 必备 默认值 兼容性 描述
errMsg string -
错误信息