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

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

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

使用node环境,在vscode 工具中,创建 app.js 文件 ,代码如下,记得安装 npm install websocket 和 npm install http 模块 。

开启 websocket接口服务后,就可以去封装小程序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)
  }
}

原文地址:
https://developers.weixin.qq.com/community/develop/article/doc/000a0e2b1a0378d5ce6818c535b813

Comments are closed.