uni.connectSocket(options)
创建一个 WebSocket 连接。
connectSocket 兼容性
| Web | 微信小程序 | Android | iOS | iOS uni-app x UTS 插件 | HarmonyOS |
| 4.0 | 4.41 | 3.91 | 4.11 | 4.11 | 4.61 |
参数
| 名称 | 类型 | 必填 | 默认值 | 兼容性 | 描述 |
| options | ConnectSocketOptions | 是 | | | |
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 | | url | string | 是 | | | 开发者服务器接口地址 | | header | UTSJSONObject | 否 | null | | HTTP 请求 Header,header 中不能设置 Referer | | protocols | Array<string> | 否 | null | | 子协议数组 | | success | (result: ConnectSocketSuccess) => void | 否 | null | | 接口调用成功的回调函数 | | fail | (result: ConnectSocketFail) => void | 否 | null | | 接口调用失败的回调函数 | | complete | (result: any) => void | 否 | null | | 接口调用结束的回调函数(调用成功、失败都会执行) | | forceCellularNetwork | boolean | 否 | | | 需要基础库: 2.29.0
强制使用蜂窝网络发送请求
| | perMessageDeflate | boolean | 否 | | | 需要基础库: 2.8.0
是否开启压缩扩展
| | tcpNoDelay | boolean | 否 | | | 需要基础库: 2.4.0
建立 TCP 连接的时候的 TCP_NODELAY 设置
| | timeout | number | 否 | | | 需要基础库: 2.10.0
超时时间,单位为毫秒
|
|
ConnectSocketSuccess 的属性值
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 |
| errMsg | string | 是 | | | |
ConnectSocketFail 的属性值
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 |
| errCode | number | 是 | | | 错误码 - 600009 URL格式不合法 |
| errSubject | string | 是 | | | 统一错误主题(模块)名称 |
| data | any | 否 | | | 错误信息中包含的数据 |
| cause | Error | 否 | | | 源错误信息,可以包含多个错误,详见SourceError |
| errMsg | string | 是 | | | |
返回值
SocketTask 的方法
send(options: SendSocketMessageOptions): void;
send
通过 WebSocket 连接发送数据
send 兼容性
| Web | 微信小程序 | Android | iOS | iOS uni-app x UTS 插件 | HarmonyOS |
| 4.0 | 4.41 | 3.91 | 4.11 | 4.11 | 4.61 |
参数
| 名称 | 类型 | 必填 | 默认值 | 兼容性 | 描述 |
| options | SendSocketMessageOptions | 是 | | | |
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 | | data | any | 是 | | | 需要发送的内容, app平台从 4.61 版本开始支持ArrayBuffer | | success | (result: GeneralCallbackResult) => void | 否 | null | | 接口调用成功的回调函数 | | fail | (result: SendSocketMessageFail) => void | 否 | null | | 接口调用失败的回调函数 | | complete | (result: any) => void | 否 | null | | 接口调用结束的回调函数(调用成功、失败都会执行) |
|
SendSocketMessageFail 的属性值
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 |
| errCode | number | 是 | | | 错误码 |
| 合法值 | 描述 | | 10001 | 发送数据超限,发送队列不能超过16M大小。 | | 10002 | websocket未连接 | | 602001 | websocket系统错误 |
|
| errSubject | string | 是 | | | 统一错误主题(模块)名称 |
| data | any | 否 | | | 错误信息中包含的数据 |
| cause | Error | 否 | | | 源错误信息,可以包含多个错误,详见SourceError |
| errMsg | string | 是 | | | |
close(options: CloseSocketOptions): void;
close
关闭 WebSocket 连接
close 兼容性
| Web | 微信小程序 | Android | iOS | iOS uni-app x UTS 插件 | HarmonyOS |
| 4.0 | 4.41 | 3.91 | 4.11 | 4.11 | 4.61 |
参数
| 名称 | 类型 | 必填 | 默认值 | 兼容性 | 描述 |
| options | CloseSocketOptions | 是 | | | |
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 | | code | number | 否 | 1000 | | 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。如果这个参数没有被指定,默认的取值是1000 (表示正常连接关闭) | | reason | string | 否 | "" | | 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于123字节的UTF-8 文本(不是字符) | | success | (result: GeneralCallbackResult) => void | 否 | null | | 接口调用成功的回调函数 | | fail | (result: GeneralCallbackResult) => void | 否 | null | | 接口调用失败的回调函数 | | complete | (result: GeneralCallbackResult) => void | 否 | null | | 接口调用结束的回调函数(调用成功、失败都会执行) |
|
onOpen(callback: (result: OnSocketOpenCallbackResult) => void): void;
onOpen
监听 WebSocket 连接打开事件
onOpen 兼容性
| Web | 微信小程序 | Android | iOS | iOS uni-app x UTS 插件 | HarmonyOS |
| 4.0 | 4.41 | 3.91 | 4.11 | 4.11 | 4.61 |
参数
OnSocketOpenCallbackResult 的属性值
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 |
| header | any | 是 | | | 连接成功的 HTTP 响应 Header |
onClose(callback: (result: any) => void): void;
onClose
监听 WebSocket 连接关闭事件
onClose 兼容性
| Web | 微信小程序 | Android | iOS | iOS uni-app x UTS 插件 | HarmonyOS |
| 4.0 | 4.41 | 3.91 | 4.11 | 4.11 | 4.61 |
参数
| 名称 | 类型 | 必填 | 默认值 | 兼容性 | 描述 |
| callback | (result: any) => void | 是 | | | |
onError(callback: (result: GeneralCallbackResult) => void): void;
onError
监听 WebSocket 错误
onError 兼容性
| Web | 微信小程序 | Android | iOS | iOS uni-app x UTS 插件 | HarmonyOS |
| 4.0 | 4.41 | 3.91 | 4.11 | 4.11 | 4.61 |
参数
onMessage(callback: (result: OnSocketMessageCallbackResult) => void): void;
onMessage
监听 WebSocket 接受到服务器的消息事件
onMessage 兼容性
| Web | 微信小程序 | Android | iOS | iOS uni-app x UTS 插件 | HarmonyOS |
| 4.0 | 4.41 | 3.91 | 4.11 | 4.11 | 4.61 |
参数
OnSocketMessageCallbackResult 的属性值
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 |
| data | any | 是 | | | 服务器返回的消息, app平台从 4.61 版本开始支持ArrayBuffer |
参见
uni.onSocketOpen(options)
监听WebSocket连接打开事件。 已废弃,使用 SocketTask 的 onOpen 替换。
onSocketOpen 兼容性
| Web | 微信小程序 | Android | iOS | iOS uni-app x UTS 插件 | HarmonyOS |
| 4.0 | 4.41 | 3.91 | 4.11 | 4.11 | 4.61 |
参数
参见
uni.onSocketError(callback)
监听WebSocket错误。 已废弃,使用 SocketTask 的 onError 替换。
onSocketError 兼容性
| Web | 微信小程序 | Android | iOS | iOS uni-app x UTS 插件 | HarmonyOS |
| 4.0 | 4.41 | 3.91 | 4.11 | 4.11 | 4.61 |
参数
OnSocketErrorCallbackResult 的属性值
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 |
| errMsg | string | 是 | | | 错误信息 |
参见
uni.sendSocketMessage(options)
通过 WebSocket 连接发送数据,需要先 uni.connectSocket,并在 uni.onSocketOpen 回调之后才能发送。 已废弃,使用 SocketTask 的 send 替换。
sendSocketMessage 兼容性
| Web | 微信小程序 | Android | iOS | iOS uni-app x UTS 插件 | HarmonyOS |
| 4.0 | 4.41 | 3.91 | 4.11 | 4.11 | 4.61 |
参数
| 名称 | 类型 | 必填 | 默认值 | 兼容性 | 描述 |
| options | SendSocketMessageOptions | 是 | | | |
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 | | data | any | 是 | | | 需要发送的内容, app平台从 4.61 版本开始支持ArrayBuffer | | success | (result: GeneralCallbackResult) => void | 否 | null | | 接口调用成功的回调函数 | | fail | (result: SendSocketMessageFail) => void | 否 | null | | 接口调用失败的回调函数 | | complete | (result: any) => void | 否 | null | | 接口调用结束的回调函数(调用成功、失败都会执行) |
|
SendSocketMessageFail 的属性值
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 |
| errCode | number | 是 | | | 错误码 |
| 合法值 | 描述 | | 10001 | 发送数据超限,发送队列不能超过16M大小。 | | 10002 | websocket未连接 | | 602001 | websocket系统错误 |
|
| errSubject | string | 是 | | | 统一错误主题(模块)名称 |
| data | any | 否 | | | 错误信息中包含的数据 |
| cause | Error | 否 | | | 源错误信息,可以包含多个错误,详见SourceError |
| errMsg | string | 是 | | | |
参见
注意事项
- 出于性能的权衡,在底层实现上发送队列占用的内存不能超过16M,一旦超过将导致连接被关闭。
uni.onSocketMessage(callback)
监听WebSocket接受到服务器的消息事件。 已废弃,使用 SocketTask 的 onMessage 替换。
onSocketMessage 兼容性
| Web | 微信小程序 | Android | iOS | iOS uni-app x UTS 插件 | HarmonyOS |
| 4.0 | 4.41 | 3.91 | 4.11 | 4.11 | 4.61 |
参数
OnSocketMessageCallbackResult 的属性值
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 |
| data | any | 是 | | | 服务器返回的消息, app平台从 4.61 版本开始支持ArrayBuffer |
参见
uni.closeSocket(options)
关闭 WebSocket 连接。 已废弃,使用 SocketTask 的 close 替换。
closeSocket 兼容性
| Web | 微信小程序 | Android | iOS | iOS uni-app x UTS 插件 | HarmonyOS |
| 4.0 | 4.41 | 3.91 | 4.11 | 4.11 | 4.61 |
参数
| 名称 | 类型 | 必填 | 默认值 | 兼容性 | 描述 |
| options | CloseSocketOptions | 是 | | | |
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 | | code | number | 否 | 1000 | | 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。如果这个参数没有被指定,默认的取值是1000 (表示正常连接关闭) | | reason | string | 否 | "" | | 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于123字节的UTF-8 文本(不是字符) | | success | (result: GeneralCallbackResult) => void | 否 | null | | 接口调用成功的回调函数 | | fail | (result: GeneralCallbackResult) => void | 否 | null | | 接口调用失败的回调函数 | | complete | (result: GeneralCallbackResult) => void | 否 | null | | 接口调用结束的回调函数(调用成功、失败都会执行) |
|
参见
uni.onSocketClose(callback)
监听WebSocket关闭。 已废弃,使用 SocketTask 的 onClose 替换。
onSocketClose 兼容性
| Web | 微信小程序 | Android | iOS | iOS uni-app x UTS 插件 | HarmonyOS |
| 4.0 | 4.41 | 3.91 | 4.11 | 4.11 | 4.61 |
参数
OnSocketCloseCallbackResult 的属性值
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 |
| code | number | 是 | | | 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。 |
| reason | string | 是 | | | 一个可读的字符串,表示连接被关闭的原因。 |
参见
示例
示例为hello uni-app x alpha分支,与最新HBuilderX Alpha版同步。与最新正式版同步的master分支示例另见
扫码体验 示例源码如下,请查看 pre > code 标签中的内容
<template>
<page-head title="websocket通讯示例"></page-head>
<view class="uni-padding-wrap">
<view class="uni-btn-v">
<text class="websocket-msg">{{ showMsg }}</text>
<button class="uni-btn-v" type="primary" @click="connect">
连接websocket服务
</button>
<button class="uni-btn-v" v-show="connected" type="primary" @click="send">
发送一条消息
</button>
<button class="uni-btn-v" type="primary" @click="close">
断开websocket服务
</button>
<text class="websocket-tips">发送消息后会收到一条服务器返回的消息(与发送的消息内容一致)</text>
<text
class="websocket-tips">web端和小程序端uni-push功能、app-android端和app-ios端的web-view组件日志回显、app-harmony端的日志回显会占用一个socket链接,此时使用全局的socket
api会引发混乱。应使用socketTask操作websocket链接。</text>
<text class="websocket-tips">小程序端日志回显功能也会占用一个socket链接,如果不希望使用此功能可以在HBuilderX控制台关闭日志回显。</text>
<button class="uni-btn-v" type="primary" @click="goSocketTask">
跳转 socketTask 示例
</button>
</view>
</view>
</template>
<script setup lang="uts">
const connected = ref(false)
const connecting = ref(false)
const msg = ref('')
const roomId = ref('')
const platform = ref('')
const showMsg = computed(() : string => {
if (connected.value) {
if (msg.value.length > 0) {
return '收到消息:' + msg.value
} else {
return '等待接收消息'
}
} else {
return '尚未连接'
}
})
onLoad(() => {
platform.value = uni.getDeviceInfo().platform as string
})
onUnload(() => {
uni.closeSocket({
code: 1000,
reason: 'close reason from client',
success: (res : any) => {
console.log('uni.closeSocket success', res)
},
fail: (err : any) => {
console.log('uni.closeSocket fail', err)
},
} as CloseSocketOptions)
uni.hideLoading()
})
const connect = () => {
if (connected.value || connecting.value) {
uni.showModal({
content: '正在连接或者已经连接,请勿重复连接',
showCancel: false,
})
return
}
connecting.value = true
uni.showLoading({
title: '连接中...',
})
uni.connectSocket({
url: 'wss://websocket.dcloud.net.cn',
header:{
"test":"uniapp x"
},
protocols: null,
success: (res : any) => {
// 这里是接口调用成功的回调,不是连接成功的回调,请注意
console.log('uni.connectSocket success', res)
},
fail: (err : any) => {
// 这里是接口调用失败的回调,不是连接失败的回调,请注意
console.log('uni.connectSocket fail', err)
},
})
uni.onSocketOpen((res) => {
connecting.value = false
connected.value = true
uni.hideLoading()
uni.showToast({
icon: 'none',
title: '连接成功',
})
console.log('onOpen', res)
})
uni.onSocketError((err) => {
connecting.value = false
connected.value = false
uni.hideLoading()
uni.showModal({
content: '连接失败,可能是websocket服务不可用,请稍后再试',
showCancel: false,
})
console.log('onError', err)
})
uni.onSocketMessage((res) => {
if (res.data instanceof ArrayBuffer) {
var int8 = new Int8Array(res.data)
msg.value = int8.toString()
console.log('onMessage', res)
} else {
msg.value = res.data as string
console.log('onMessage', res)
}
})
uni.onSocketClose((res) => {
connected.value = false
msg.value = ''
console.log('onClose', res)
})
}
const send = () => {
uni.sendSocketMessage({
data:
'from ' +
platform.value +
' : ' +
parseInt((Math.random() * 10000).toString()).toString(),
success: (res : any) => {
console.log(res)
},
fail: (err : any) => {
console.log(err)
},
} as SendSocketMessageOptions)
}
const close = () => {
uni.closeSocket({
code: 1000,
reason: 'close reason from client',
success: (res : any) => {
console.log('uni.closeSocket success', res)
},
fail: (err : any) => {
console.log('uni.closeSocket fail', err)
},
} as CloseSocketOptions)
}
const goSocketTask = () => {
uni.navigateTo({
url: '/pages/API/websocket/socketTask',
})
}
</script>
<style>
.uni-btn-v {
padding: 5px 0;
}
.uni-btn-v {
margin: 10px 0;
}
.websocket-msg {
padding: 40px 0px;
text-align: center;
font-size: 14px;
line-height: 40px;
color: #666666;
}
.websocket-tips {
padding: 10px 0px;
text-align: center;
font-size: 14px;
line-height: 24px;
color: #666666;
}
</style>
通用类型
GeneralCallbackResult
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 |
| errMsg | string | 是 | | | 错误信息 |