Browse Source

feat: 网络调整

master
WIN-87ES3P38OPV\EDY 1 month ago
parent
commit
284617f60a
  1. 2
      main.js
  2. 35
      preload.js

2
main.js

@ -5,6 +5,8 @@ const { SensorController } = require('./src/business/sensor-controller')
const { UsbSerialBridge } = require('./src/business/usb-serial-bridge') const { UsbSerialBridge } = require('./src/business/usb-serial-bridge')
const pkg = require('./package.json') const pkg = require('./package.json')
if (require('electron-squirrel-startup')) app.quit()
const cacheDir = app.getPath('userData') const cacheDir = app.getPath('userData')
const cacheFile = path.join(cacheDir, 'app-cache.json') const cacheFile = path.join(cacheDir, 'app-cache.json')
const fileRoot = path.join(cacheDir, 'files') const fileRoot = path.join(cacheDir, 'files')

35
preload.js

@ -10,6 +10,7 @@
const { contextBridge, ipcRenderer } = require('electron') const { contextBridge, ipcRenderer } = require('electron')
const nodeNet = require('net') const nodeNet = require('net')
const dns = require('dns') const dns = require('dns')
const { execFile } = require('child_process')
function tryConnect(host, port, timeout) { function tryConnect(host, port, timeout) {
return new Promise((resolve) => { return new Promise((resolve) => {
@ -22,17 +23,41 @@ function tryConnect(host, port, timeout) {
}) })
} }
function normalizePingHost(input) {
const raw = String(input || '').trim()
if (!raw) return ''
try {
return new URL(raw).hostname
} catch {}
return raw.replace(/^https?:\/\//i, '').split('/')[0].split(':')[0]
}
function trySystemPing(host, timeout) {
return new Promise((resolve) => {
const wait = Math.max(1000, Number(timeout) || 2000)
execFile('ping', ['-n', '1', '-w', String(wait), host], { windowsHide: true }, (err) => {
resolve(!err)
})
})
}
const net = { const net = {
async ping(host, timeout) { async ping(host, timeout) {
const target = normalizePingHost(host)
if (!target) return false
const wait = Math.max(1000, Number(timeout) || 2000)
const isIp = nodeNet.isIP(target) !== 0
try { try {
await dns.promises.resolve(host) if (!isIp) await dns.promises.lookup(target)
} catch { } catch {
return false if (!await trySystemPing(target, wait)) return false
} }
for (const port of [443, 80]) {
if (await tryConnect(host, port, timeout)) return true for (const port of [443, 80, 53]) {
if (await tryConnect(target, port, wait)) return true
} }
return false return trySystemPing(target, wait)
} }
} }

Loading…
Cancel
Save