my.sendSocketMessage
Use this API to send data over WebSocket connection. Call my.connectSocket first and send data after the my.onSocketOpen callback.
Prerequisites:
- Supported SDK versions:
- Android: 2.67.0
- iOS: 2.80.0
- Supported types of mini programs: DSL
Sample code
See the following JavaScript sample code:
// send text message
my.sendSocketMessage({
data: 'Hello Server',
success: (res) => {
console.log('Succeed to send the message');
},
fail: (err) => {
console.log('Failed to send the message:', err.errorMessage);
}
});
// Send JSON data
my.sendSocketMessage({
data: JSON.stringify({ type: 'chat', content: 'hello' }),
success: () => {
console.log('Succeed to send JSON data');
}
});Parameters
The incoming parameter is of the Object type with the following properties:
Property | Data type | Required | Description |
data | String/ArrayBuffer | Yes | The data to be sent, in text string or Base64-encoded string. |
isBuffer | Boolean | No | Indicates whether the data is Base64-encoded string:
|
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 |
10 | Messages cannot be sent until the connection is established. | Check the WebSocket connection status. If the connection is disconnected, it needs to be re-established. Refer to the my.connectSocket JSAPI. |
FAQ
When can messages be sent via the my.sendSocketMessage JSAPI?
If want to send messages over WebSocket connection via the my.sendSocketMessage JSAPI, must call my.connectSocket first and send data after the my.onSocketOpen callback. Currently, the WebSocket connection is fully established.
Sample code:
You should send messages inside the my.onSocketOpen callback.
let isConnected = false;
my.connectSocket({
url: 'wss://example.com/socket'
});
//wait to enable the connection
my.onSocketOpen(function() {
isConnected = true;
//send messages after WebSocket connection is fully established
my.sendSocketMessage({
data: 'Hello',
success: () => {
console.log('send successfully');
}
});
});
my.onSocketError(function(err) {
console.log('Failed to connect:', err.errorMessage);
});How to send binary data via the my.sendSocketMessage JSAPI?
To send binary data, data must be provided as a Base64-encoded string. For more information, see the isBuffer parameter of the my.sendSocketMessage JSAPI.
// send Base64-encoded string
my.sendSocketMessage({
data: 'AQIDBA==', // Base64 encoding
isBuffer: true,
success: () => {
console.log('send successfully');
}
});