Skip to content

WebSocket

Description

It is recommended to use the SocketTask method to manage the webSocket link. The life cycle of each link is more controllable. When there are multiple webSocket links at the same time, using the wx prefix method may cause some inconsistencies with expectations.

sendSocketMessage

TIP

The API usage is as follows: wx.sendSocketMessage(Object object)

  • Functional description: Send data through the WebSocket connection. Need towx.connectSocket first, and wx.onSocketOpen after the callback can it be sent.。

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    datastring/ArrayBuffer-YesContent to be sent
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Sample code:

js
let socketOpen = false
let socketMsgQueue = []
wx.connectSocket({
  url: 'test.php'
})

wx.onSocketOpen(function(res) {
  socketOpen = true
  for (let i = 0; i < socketMsgQueue.length; i++){
    sendSocketMessage(socketMsgQueue[i])
  }
  socketMsgQueue = []
})

function sendSocketMessage(msg) {
  if (socketOpen) {
    wx.sendSocketMessage({
      data:msg
    })
  } else {
    socketMsgQueue.push(msg)
  }
}

onSocketOpen

TIP

The API usage is as follows: wx.onSocketOpen(function listener)

  • Functional description: Listen for WebSocket connection opening events

  • Parameters and descriptions: function listener, Listener function for the WebSocket connection opening event.。

    PropertiesTypeDescription
    headerobjectHTTP response header for successful connection

onSocketMessage

TIP

The API usage is as follows: wx.onSocketMessage(function listener)

  • Functional description: Listen for the WebSocket message event received by the server.

  • Parameters and descriptions: function listener, Listener function for the WebSocket message event received by the server.。

    PropertiesTypeDescription
    datastring/ArrayBufferMessage returned by the server

onSocketError

TIP

The API usage is as follows: wx.onSocketError(function listener)

  • Functional description: Listen for the WebSocket error event.

  • Parameters and descriptions: function listener, Listener function for the WebSocket error event.。

    PropertiesTypeDescription
    errMsgstringError message

onSocketClose

TIP

The API usage is as follows: wx.onSocketClose(function listener)

  • Functional description: Listen for WebSocket connection closing events.

  • Parameters and descriptions: function listener, Listener function for WebSocket connection closing events.。

    PropertiesTypeDescription
    codenumberA numeric value indicates the status number of the closed connection, indicating the reason why the connection was closed
    reasonreasonA readable string indicating the reason why the connection was closed

connectSocket

TIP

The API usage is as follows: SocketTask wx.connectSocket(Object object)

  • Functional description: Create a WebSocket connection. Please read carefully before use Related instructions.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    urlstring-YesThe developer server wss interface address
    headerObject-NoHTTP Header, Referer cannot be set in the Header
    protocolsArray.<string>-NoSubprotocol array
    tcpNoDelaybooleanfalseNoTCP_NODELAY setting when establishing a TCP connection
    timeoutnumber-NoTimeout in milliseconds
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Return value: SocketTask

  • Number of concurrent connections

    • Versions 1.5.0 and above can have up to 5 WebSocket connections at the same time.
    • Versions below 1.5.0 can only have one WebSocket connection at a time for a mini program. If a WebSocket connection already exists, it will be automatically closed and a new WebSocket connection will be created.
  • Sample code:

js
wx.connectSocket({
  url: 'wss://example.qq.com',
  header:{
    'content-type': 'application/json'
  },
  protocols: ['protocol1']
})

closeSocket

TIP

The API usage is as follows: wx.closeSocket(Object object)

  • Functional description: To close a WebSocket connection, use the following method.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    codenumber1003 (indicates a normal connection closure)NoA numeric value indicates the status number of the closed connection, indicating the reason why the connection is closed
    reasonstring-NoA readable string indicating the reason why the connection is closed. This string must be UTF-8 text (not characters) not longer than 123 bytes
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Sample code:

js
wx.connectSocket({
  url: 'test.php'
})

//Please note that there may be timing issues here,
//If wx.connectSocket has not yet called back wx.onSocketOpen, and wx.closeSocket is called first, then the purpose of closing the WebSocket cannot be achieved.
//It is imperative to call wx.closeSocket during the WebSocket's open period to effectuate closure.
wx.onSocketOpen(function() {
  wx.closeSocket()
})

wx.onSocketClose(function(res) {
  console.log('WebSocket has been closed!')
})

SocketTask

.close

TIP

The API usage is as follows: SocketTask.close(Object object)

  • Functional description: Close the WebSocket connection.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    codenumber1003 (indicates a normal connection closure)NoA numeric value indicates the status number of the closed connection, indicating the reason why the connection is closed
    reasonstring-NoA readable string indicating the reason why the connection is closed. This string must be UTF-8 text (not characters) not longer than 123 bytes
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)

.onClose

TIP

The API usage is as follows: SocketTask.onClose(function listener)

  • Functional description: Listen for WebSocket connection closing events.

  • Parameters and descriptions: function listener, Listener function for WebSocket connection closing events.。

    PropertiesTypeDescription
    codenumberA numeric value indicates the status number of the closed connection, indicating the reason why the connection was closed
    reasonreasonA readable string indicating the reason why the connection was closed

.onError

TIP

The API usage is as follows: SocketTask.onError(function listener)

  • Functional description: Listen for the WebSocket error event.

  • Parameters and descriptions: function listener, Listener function for the WebSocket error event.。

    PropertiesTypeDescription
    errMsgstringError message

.onMessage

TIP

The API usage is as follows: SocketTask.onMessage(function listener)

  • Functional description: Listen for the WebSocket message event received by the server.

  • Parameters and descriptions: function listener, Listener function for the WebSocket message event received by the server.。

    PropertiesTypeDescription
    datastring/ArrayBufferMessage returned by the server

.onOpen

TIP

The API usage is as follows: SocketTask.onOpen(function listener)

  • Functional description: Listen for WebSocket connection opening events

  • Parameters and descriptions: function listener, Listener function for the WebSocket connection opening event.。

    PropertiesTypeDescription
    headerobjectHTTP response header for successful connection

.send

TIP

The API usage is as follows: SocketTask.send(Object object)

  • Functional description: Send data through WebSocket connection

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    datastring/ArrayBuffer-YesContent to be sent
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)