title: Taro.connectSocket(option)

sidebar_label: connectSocket

Creates a WebSocket connection. Read related instructions before use.

Number of Concurrent Connections

  • In version 1.7.0 or later, up to 5 WebSocket connections can exist at the same time.

  • Before version 1.7.0, a mini program can only have one WebSocket connection at a time.If a WebSocket connection already exists, it will be automatically disabled and a new one will be created.

Reference

Type

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

Parameters

Option

Property Type Required Description
url string Yes The wss API URL of developer server
header Record<string, any> No HTTP Header. Referer is not available in Header.
protocols string[] No Sub-protocol array
tcpNoDelay boolean No TCP_NODELAY settings when a TCP connection is established
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

Example 1

  1. Taro.connectSocket({
  2. url: 'wss://example.qq.com',
  3. header:{
  4. 'content-type': 'application/json'
  5. },
  6. protocols: ['protocol1']
  7. })

Example 2

  1. Taro.connectSocket({
  2. url: 'ws://echo.websocket.org/echo',
  3. success: function () {
  4. console.log('connect success')
  5. }
  6. }).then(task => {
  7. task.onOpen(function () {
  8. console.log('onOpen')
  9. task.send({ data: 'xxx' })
  10. })
  11. task.onMessage(function (msg) {
  12. console.log('onMessage: ', msg)
  13. task.close()
  14. })
  15. task.onError(function () {
  16. console.log('onError')
  17. })
  18. task.onClose(function (e) {
  19. console.log('onClose: ', e)
  20. })
  21. })

API Support

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