Skip to main content
Version: 3.x

Taro.sendSocketMessage(option)

通过 WebSocket 连接发送数据。需要先 Taro.connectSocket,并在 Taro.onSocketOpen 回调之后才能发送。

参考文档

类型#

(option: Option) => Promise<CallbackResult>

参数#

Option#

参数类型必填说明
datastring | ArrayBuffer需要发送的内容
complete(res: CallbackResult) => void接口调用结束的回调函数(调用成功、失败都会执行)
fail(res: CallbackResult) => void接口调用失败的回调函数
success(res: CallbackResult) => void接口调用成功的回调函数

示例代码#

let socketOpen = false
const socketMsgQueue = []
Taro.connectSocket({
url: 'test.php'
})
Taro.onSocketOpen(function(res) {
socketOpen = true
for (let i = 0; i < socketMsgQueue.length; i++){
sendSocketMessage(socketMsgQueue[i])
}
socketMsgQueue = []
})
function sendSocketMessage(msg) {
if (socketOpen) {
Taro.sendSocketMessage({
data:msg
})
} else {
socketMsgQueue.push(msg)
}
}

API 支持度#

API微信小程序百度小程序支付宝小程序H5React Native
Taro.sendSocketMessage✔️✔️✔️