原理是本地写一个config.json,把初始端口放进去,每次启动electron的socket服务时如果发现端口被占用,就更新config.json里的端口号加1,并保存到config.json,然后退出并重启electron,直到找到可用的端口

{"port":1081}
const { app, BrowserWindow, protocol, dialog } = require("electron");
const path = require("path");
const { Menu } = require("electron");
const myMenu = require("./src/menu.js");
const WebSocket = require("ws");
const fs = require("fs");
//wss通讯服务
let wss = {};
openWs();
function openWs() {
fs.readFile("config.json", "utf-8", (err, configFileDataRes) => {
if (err) {
dialog.showMessageBox({
type: "info",
title: "读取配置文件失败",
message: "请重新安装",
detail: JSON.stringify(err),
});
throw err;
}
const configFileData = JSON.parse(configFileDataRes);
try {
wss = new WebSocket.Server({ port: configFileData.port });
} catch (error) {
console.log("创建webSocket失败:", error);
}
wss.on("connection", (ws) => {
console.log(ws, configFileData.port + "成功了");
/** 调用原生electron接口
* {"type":"open_page","src":"pages/play/index.html","big":true}
*/
ws.on("message", (message) => {
message = JSON.parse(message);
if (message.type == "open_page") {
const win = new BrowserWindow();
win.loadFile(message.src);
win.webContents.openDevTools({ mode: "detach" });
if (message.big) {
win.maximize();
}
}
});
ws.send("something");
});
wss.on("error", (ws) => {
storeData({ port: parseInt(configFileData.port) + 1 }, "config.json");
app.exit();
app.relaunch();
});
});
}
// /wss通讯服务