SocketTask.send

Send data over WebSocket connection. Call my.connectSocket first and send data after the SocketTask.onOpen 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:

copy
// send text message
const socketTask = my.connectSocket({
  url: 'wss://...',
  multiple: true
});
// listen whether the WebSocket connection is established successfully
socketTask.onOpen(function(res) {
  // can send messages after the WebSocket connection is established successfully
  socketTask.send({
    data:'hi'
  })
});

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 binary.

The default value is false. When set to true, data must be provided as a 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. 0 indicates success. For more information, see the following Error code section.

errorMessage

String

The error message.

Error codes

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.

FAQs

When messages can be sent via SocketTask.send?

Messages can only be sent after the SocketTask.onOpen callback is triggered. At this point, the WebSocket connection is fully established.

See the following sample code as the solution:

copy
let isConnected = false;

const socketTask = my.connectSocket({
  url: 'wss://...',
  multiple: true
});
// listen whether the WebSocket connection is established successfully
socketTask.onOpen(function(res) {
  // send messages after the WebSocket connection is established successfully
  socketTask.send({
    data:'hi'
  })
});