This article only applies to the electron project generated using the electron-vue template, and related configuration is also carried out around it. Of course, the electron engineering generated by vuecli3 can also be referred to.
For the electron-vue project, the default 9080 port may be occupied by default, so the APPLICATION of HTTP service should use self-judgment to ensure that the port is available.
Electron references the flash plug-in packaging example
Implementing judgment logic
/lib/utils/ create portIsOccupied. Js file to check port usage, inject variable DEV_PORT into process environment, and return available ports, so that the host process page can read available ports through process environment. You can also get the available ports returned through promise.resolve ().
const net = require('net')
function portIsOccupied(port) {
const server = net.createServer().listen(port)
return new Promise((resolve, reject) = > {
server.on('listening'.() = > {
console.log(`the server is runnint on port ${port}`)
server.close()
// Share state by injecting process environment variables
process.env.DEV_PORT = port
process.env.PROD_PORT = port
// Return the available port
resolve(port)
})
server.on('error'.(err) = > {
if (err.code === 'EADDRINUSE') {
// Use port number +1
resolve(portIsOccupied(port + 1))
console.log(`this port ${port} is occupied.try another.`)}else {
reject(err)
}
})
})
}
module.exports = portIsOccupied
Copy the code
Configure ports in development mode
Because the project uses the electron- VUE generation engineering, the electron engineering structure is different from the current mainstream vuecli3 generation, but the logic is basically the same. The following is the configuration for the electron- Vue project.
Find the project /.electron/dev-runner. Js file and you can see that the service is running through the WebpackDevServer plugin, where the port is written down to 9080.
const server = new WebpackDevServer(
compiler,
{
contentBase: path.join(__dirname, '.. / '),
quiet: true,
before (app, ctx) {
app.use(hotMiddleware)
ctx.middleware.waitUntilValid(() = > {
resolve()
})
}
}
)
server.listen(9080)
Copy the code
With some modifications, you can use the free ports to keep your application running by introducing the functions written above.
const portIsOccupied = require('.. /lib/utils/portIsOccupied')... ... portIsOccupied(9080).then(port= > {
server.listen(port)
})
Copy the code
Configure ports in production mode
In the main thread file/SRC /main/index.js, a judgment function is introduced to determine the production mode, and express is used as the HTTP static server for local packaged files, so that Flash can load normally.
The original localServer function for writing dead ports is reformed and port judgment function is introduced.
before
:
function localServer() {
let server = express()
server.use(express.static(__dirname))
server.listen(9080)}Copy the code
after
:
import portIsOccupied from '.. /.. /lib/utils/portIsOccupied'
function localServer() {
// Sync with await with promise
return new Promise((resolve, reject) = > {
let server = express()
server.use(express.static(__dirname))
portIsOccupied(9080).then(port= > {
server.listen(port)
resolve(port)
})
})
}
Copy the code
After the localServer function is executed in production mode, available ports can be read from the process environment at any location to ensure successful service startup.
A complete logic
/ SRC /main/index.js
import { app, BrowserWindow } from 'electron'
import express from 'express'
// Introduce a function to automatically determine port availability
import portIsOccupied from '.. /.. /lib/utils/portIsOccupied'
/** * Set `__static` path to static files in production * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html */
if(process.env.NODE_ENV ! = ='development') {
global.__static = require('path').join(__dirname, '/static').replace(/\\/g.'\ \ \ \')}// the packaged files are loaded with the "file://" protocol by default
// because flash does not allow loading in the "file://" protocol, to solve flash loading security issues
// Use Express as a local server so that pages run on the local HTTP port service
function localServer() {
// Sync with await with promise
return new Promise((resolve, reject) = > {
let server = express()
server.use(express.static(__dirname));
portIsOccupied(9080).then(port= > {
server.listen(port)
resolve(port)
})
})
}
let mainWindow
let flashPlugins = process.arch == 'x64'
? require('path').resolve(__dirname, '.. /.. /lib/pepflashplayer64_29_0_0_238.dll')
: require('path').resolve(__dirname, '.. /.. /lib/pepflashplayer32_29_0_0_238.dll')
if (__dirname.includes(".asar")) {
flashPlugins = process.arch == 'x64'
? require('path').join(process.resourcesPath + '/lib/pepflashplayer64_29_0_0_238.dll')
: require('path').join(process.resourcesPath + '/lib/pepflashplayer32_29_0_0_238.dll')
}
app.commandLine.appendSwitch('ppapi-flash-path', flashPlugins);
app.commandLine.appendSwitch('ppapi-flash-version'.'29.0.0.238');
async function createWindow () {
if (process.env.NODE_ENV === "production") {
// Use async/await to implement synchronous waiting and ensure that process.env.prod_port is assigned
await localServer()
}
const winURL = process.env.NODE_ENV === 'development'
? `http://localhost:${process.env.DEV_PORT}`
// : `file://${__dirname}/index.html`
// resolve flash not allowing loading in the "file://" protocol
: `http://localhost:${process.env.PROD_PORT}/index.html`
/** * Initial window options */
mainWindow = new BrowserWindow({
height: 900.width: 1600.useContentSize: true.frame: false.center: true.fullscreenable: false.// Whether to allow full screen
center: true.// Whether it appears in the center of the screen
title: 'electron-rtmp'.backgroundColor: '#fff'.// Background color for Transparent and Frameless Windows
titleBarStyle: 'hidden'.// Title bar styles include Hidden, hiddenInset, customButtonsOnHover, etc
resizable: false.// Whether the stretch size is allowed
'webPreferences': {
plugins: true.webSecurity: false.defaultFontFamily: {
standard: "Microsoft YaHei".defaultEncoding: "utf-8"}}})if (process.env.NODE_ENV == 'development') {
mainWindow.webContents.openDevTools()
}
mainWindow.loadURL(winURL)
mainWindow.on('closed'.() = > {
mainWindow = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed'.() = > {
if(process.platform ! = ='darwin') {
app.quit()
}
})
app.on('activate'.() = > {
if (mainWindow === null) {
createWindow()
}
})
Copy the code