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.
Type
(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
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
API | WeChat Mini-Program | Baidu Smart-Program | Alipay Mini-Program | H5 | React Native |
---|---|---|---|---|---|
Taro.connectSocket | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |