评论

开启websocket服务端口,调试微信websocket接口方法

小程序开发,调试websocket接口,在后端未提供websocket接口的时候,小程序开发人员自建app.js文件开启websocket服务端口,来模拟发送和解析数据,根据业务需求封装方法。

使用node环境,在vscode 工具中,创建 app.js 文件 ,代码如下,记得安装 npm install websocket 和 npm install http 模块 .
开启 websocket接口服务后,就可以去封装 官方提供的 wx.sendSocketMessage 等接口了。

const http = require("http");
const WebSocketServer = require("websocket").server;

const httpServer = http.createServer((request, response) => {
  console.log("[" + new Date() + "] Received request for " + request.url);
  response.writeHead(404);
  response.end();
});

const wsServer = new WebSocketServer({
  httpServer,
  autoAcceptConnections: true
});

wsServer.on("connect", connection => {
  connection
    .on("message", message => {
      if (message.type === "utf8") {
        console.log(">> message content from client: " + message.utf8Data);
        connection.sendUTF(message.utf8Data);   // 输出内容返回给前端接口调用
      }
    })
    .on("close", (reasonCode, description) => {
      console.log(
        "[" +
          new Date() +
          "] Peer " +
          connection.remoteAddress +
          " disconnected."
      );
    });
});

httpServer.listen(8080, () => {
  console.log("[" + new Date() + "] Serveris listening on port 8080");
});

#小程序页面示例代码,请参考文档
const socketOpen = false
const socketMsgQueue = []
wx.connectSocket({
 // url: 'test.php',
  url :“ws://localhost:8080/”
})

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)
  }
}
点赞 2
收藏
评论

2 个评论

  • 风吹屁屁凉
    风吹屁屁凉
    2019-04-26

    不错

    2019-04-26
    赞同
    回复 1
    • 同步
      同步
      2019-04-26

      谢谢

      2019-04-26
      回复
  • 唉
    2019-04-18

    刚好是你,又刚好我要用,拿走了,谢谢

    2019-04-18
    赞同
    回复 1
    • 同步
      同步
      2019-04-26

      不客气

      2019-04-26
      回复
登录 后发表内容