Skip to main content
Version: 3.x

Taro.connectSocket(option)

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

(option: Option) => Promise<SocketTask>

Parameters

Option

PropertyTypeRequiredDescription
urlstringYesThe wss API URL of developer server
headerRecord<string, any>NoHTTP Header. Referer is not available in Header.
protocolsstring[]NoSub-protocol array
tcpNoDelaybooleanNoTCP_NODELAY settings when a TCP connection is established
complete(res: CallbackResult) => voidNoThe callback function used when the API call completed (always executed whether the call succeeds or fails)
fail(res: CallbackResult) => voidNoThe callback function for a failed API call
success(res: CallbackResult) => voidNoThe callback function for a successful API call

Sample Code

Example 1

Taro.connectSocket({
url: 'wss://example.qq.com',
header:{
'content-type': 'application/json'
},
protocols: ['protocol1']
})

Example 2

Taro.connectSocket({
url: 'ws://echo.websocket.org/echo',
success: function () {
console.log('connect success')
}
}).then(task => {
task.onOpen(function () {
console.log('onOpen')
task.send({ data: 'xxx' })
})
task.onMessage(function (msg) {
console.log('onMessage: ', msg)
task.close()
})
task.onError(function () {
console.log('onError')
})
task.onClose(function (e) {
console.log('onClose: ', e)
})
})

API Support

APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramH5React Native
Taro.connectSocket✔️✔️✔️✔️✔️