开启websocket服务端口,调试微信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)
}
}[代码]