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.

Sample Code

copy
my.connectSocket({
  url: 'test.php',
  data: {},
  header:{
    'content-type': 'application/json'
  },
});

Note:The case is only for reference. Please use your own URL to test.

Parameters

PropertyType

Required

Description
urlStringYesThe address of target server interface.
Note:
Some newly released Mini Programs only support WSS protocol.
dataObjectNoThe request parameters.
headerObjectNoHeader of the request.
successFunctionNoThe callback function for a successful API call.
failFunctionNoThe callback function for a failed API call.
completeFunctionNoThe callback function used when the API call is completed. This function is always executed no matter the call succeeds or fails.

Error Code

Error CodeDescriptionSolution
1An unknown error.-
2A network connection already exists.An Mini Program can only keep one WebSocket connection for a period of time. If a WebSocket connection already exists when a new one is created, the existing one will be automatically disabled.
3The URL parameter is null.Replace the URL link.
4An unrecognized URL format.Replace the  URL link.
5The URL must start with WS or WSS.Replace the  URL link.
6Connection timed out.Try again later.
7The HTTPS certificate returned by the server is invalid.The Mini Program must start a network request using HTTPS/WSS.  When a request is sent, the HTTPS certificate of the server domain name is checked. If the check fails, the request cannot be successfully initiated.  Due to system limitations, different platforms have different requirements for certificates. To ensure the compatibility of Mini Programs,  developers are recommended to configure certificates according to the highest standards and use relevant tools to check existing certificates to ensure that the certificates are valid.
8The protocol header returned by the server is invalid.Starting from May 2019, newly created Mini Programs must use HTTPS and WSS protocols by default and HTTP and WS protocols are not supported.
9The Sec-WebSocket-Protocol request header is not specified for the WebSocket request.Please specify the Sec-WebSocket-Protocol request header.
10The network is not available and the message cannot be sent.Please call my.sendSocketMessage to send a data message after connecting to the server normally. Use my.onSocketOpen to check if the connection with the server is correct.
Note:
To send data through a WebSocket connection, you need to use my.connectSocket to start the connection first, and then call my.sendSocketMessage to send data after the my.onSocketOpen callback.
11Failed to send message.Try again later.
12Unable to request more memory to read network data.Please check the memory.