WeChat Mini Program API Websocket


wx.connectSocket(OBJECT)


Create a WebSocket connection; a WeChat applet can only have one WebSocket connection at the same time. If a WebSocket connection currently exists, the connection will be automatically closed and Re-create a WebSocket connection.

OBJECT parameter description:

QQ截图20170208105757.png

##Sample code:

wx.connectSocket({
  url:"test.php",
  data:{
    x:"",
    y:""
  },
  header:{ 
    'content-type': 'application/json'
  },
  method:"GET"
})

wx.onSocketOpen(CALLBACK)


Listen to WebSocket connection open events

Sample code:

wx.connectSocket({
  url:"test.php"
});
wx.onSocketOpen(function(res){
  console.log("WebSocket连接已打开!")
})

wx.onSocketError(CALLBACK )


Listen for WebSocket errors

Sample code:

wx.connectSocket({
  url:"test.php"
});
wx.onSocketOpen(function(res){
  console.log("WebSocket连接已打开!")
})
wx.onSocketError(function(res){
  console.log("WebSocket连接打开失败,请检查!")
})

wx.sendSocketMessage(OBJECT)


To send data through a WebSocket connection, you need to wx.connectSocket first and then send it after the wx.onSocketOpen callback.

OBJECT parameter description:

ParameterTypeRequiredDescription##data
String is the content that needs to be sent
Sample code:

var socketOpen = false;
var socketMsgQueue = []
wx.connectSocket({
  url:"test.php"
});

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

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

Listen to the message received by WebSocket from the server Event

CALLBACK Return parameters:

Parameterdata
TypeDescription
StringMessage returned by the server
Sample code:

wx.connectSocket({
  url:"test.php"
});

wx.onSocketMessage(function(res){
  console.log("收到服务器内容:" + res.data)
})
wx.closeSocket()

Close WebSocket connection

wx.onSocketClose(CALLBACK)

Listening WebSocket close

wx.connectSocket({
  url:"test.php"
});

//注意这里有时序问题,
//如果wx.connectSocket还没回调wx.onSocketOpen,而先调用wx.closeSocket,那么就做不到关闭WebSocket的目的
//必须在WebSocket打开期间调用wx.closeSocket才能关闭
wx.onSocketOpen(function(){
  wx.closeSocket()
})

wx.onSocketClose(function(res){
  console.log("WebSocket 已关闭!")
})