【发布时间】:2020-03-06 19:15:31
【问题描述】:
我正在使用 electron 和 socket.io 设置一个 GUI 服务器应用程序。我无法获得index.html 中的onclick 按钮来运行server.js 中的startServer() 函数。我需要帮助
我尝试使用 ID 和事件侦听器来运行该函数。非常感谢您的帮助,谢谢。
main.js:
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const path = require('path')
let mainWindow
function createWindow() {
mainWindow = new BrowserWindow({
height: 500,
width: 700,
frame: false,
resizable: false,
webPreferences: {
nodeIntegration: true
}
});
// Load html into window
mainWindow.loadURL('file://' + __dirname + '/app/index.html');
mainWindow.on('closed', () => {
mainWindow = null
})
}
// Listen for app to be ready
app.on('ready', createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (mainWindow === null) {
createWindow()
}
})
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="app.css">
</head>
<body>
<script>server.js</script>
<div class="disable-highlight">
<h1>DNPS
</h1>
</div>
<input type="button" onclick="startServer()" value="Start Server" />
<script>
require('./server.js')
</script>
</body>
</html>
server.js:
const log = require('electron-log')
function startServer() {
// Load Socket.io
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.send('<h1>Hello world</h1>');
});
io.on('connection', function(socket){
log.info('a user connected')
});
http.listen(3000, function(){
log.info('listening on *:3000');
});
};
【问题讨论】:
-
您的文件
server.js的节点模块结构不正确。而且您也没有正确使用它。看一篇关于如何在 javascipt 中编写和使用模块的教程 -
有
main.js的节点模块。如果我启动main.js,那么server.js启动没有问题,如果我删除外围的function startServer() {...},但我需要function startServer() {...},所以我可以使用html 中的按钮调用该函数,但它不会让我。 -
好像
socket.io必须在脚本加载时启动,而不是在函数中调用,但我不明白为什么不能?
标签: javascript html dom socket.io electron