my.connectSocket
Use this API to create a WebSocket connection. An Mini Program can only have one WebSocket connection at a time. If a WebSocket connection already exists when a new one is created, the existing one will be automatically disabled.
Prerequisites:
- Supported SDK versions:
- Android: 2.67.0
- iOS: 2.80.0
- Supported types of mini programs: DSL
Sample Code
DSL
// create a WebSocket connection
my.connectSocket({
url: 'wss://example.com/socket',
protocols: ['chat', 'superchat'],
header: {
'content-type': 'application/json'
},
success: (res) => {
console.log('WebSocket connection request is sent');
},
fail: (err) => {
console.log('Failed to connect:', err.errorMessage);
}
});
// Listen to the event of enabling the WebSocket connection.
my.onSocketOpen(function(res) {
console.log('WebSocket connection is open');
});
// listen to the event of receiving server messages by WebSocket.
my.onSocketMessage(function(res) {
console.log('Receive the server message: ', res.data);
});Parameters
Property | Type | Required | Description |
url | String | Yes | The address of target WebSocket server. |
protocols | Array | No | Array of sub-protocols for negotiating WebSocket sub-protocols |
data | Object | No | The request parameters. |
multiple | Boolean | No | Whether to support multiple WebSocket connections. Default is |
timeout | Number | No | Connection timeout, in milliseconds. Default is 30000ms (30 seconds). |
header | Object | No | Header of the request. |
success | Function | No | The callback function for a successful API call. |
fail | Function | No | The callback function for a failed API call. |
complete | Function | No | The callback function used when the API call is completed. This function is always executed no matter the call succeeds or fails. |
success/fail/complete callback function
The following table provides the properties in the success/fail/complete callback function:
Property | Data type | Description |
error | Number | The error code. |
errorMessage | String | The error message. |
Error code
Error code | Error message | Further action |
2 | invalid parameter | Check and make sure the data type of all parameters is correct. See the previous Parameters section. |
3 |
|
|
4 | The URL format is invalid. | Check and make sure the |
5 | The URL address is not ws or wss. | Make sure only ws or wss protocol is supported. (The |
FAQ
Why cannot send messages after a WebSocket connection appears to be established successfully?
For details, see FAQ.
How to customzie the request headers when sending the my.connectSocket request?
For details, see FAQ.
How to reconnect a WebSocket connection after a connection failure?
For details, see FAQ.
Will the WebSocket disconnect after a page navigation?
For details, see FAQ.