title: Taro.sendSocketMessage(option)

sidebar_label: sendSocketMessage

Sends data over WebSocket connection. Call Taro.connectSocket first and send data after the Taro.onSocketOpen callback.

Reference

Type

  1. (option: Option) => Promise<CallbackResult>

Parameters

Option

Property Type Required Description
data string | ArrayBuffer Yes The data to be sent
complete (res: CallbackResult) => void No The callback function used when the API call completed (always executed whether the call succeeds or fails)
fail (res: CallbackResult) => void No The callback function for a failed API call
success (res: CallbackResult) => void No The callback function for a successful API call

Sample Code

  1. let socketOpen = false
  2. const socketMsgQueue = []
  3. Taro.connectSocket({
  4. url: 'test.php'
  5. })
  6. Taro.onSocketOpen(function(res) {
  7. socketOpen = true
  8. for (let i = 0; i < socketMsgQueue.length; i++){
  9. sendSocketMessage(socketMsgQueue[i])
  10. }
  11. socketMsgQueue = []
  12. })
  13. function sendSocketMessage(msg) {
  14. if (socketOpen) {
  15. Taro.sendSocketMessage({
  16. data:msg
  17. })
  18. } else {
  19. socketMsgQueue.push(msg)
  20. }
  21. }

API Support

API WeChat Mini-Program Baidu Smart-Program Alipay Mini-Program H5 React Native
Taro.sendSocketMessage ✔️ ✔️ ✔️