electron 如何解决错误:connect EISCONN::1:5555 - Local(:ffff.127.0.0.1:5555)

f8rj6qna  于 11个月前  发布在  Electron
关注(0)|答案(1)|浏览(122)

我正在制作一个电子应用程序,我需要监听本地机器上的tcp端口。当我启动应用程序时,我得到:A JavaScript error occurred in the main process Uncaught Exception:
错误:connect EISCONN::1:5555 - Local(:ffff.127.0.0.1:5555)at internalConnect(node:net 1067:16)at defaultTriggerAsyncldScope(node:internal/noc_hooks:463:18)at GetAddrInfoReqWrap. emitterfly [as callback](node:netl 324:9)at GetAddrInfoReqWrap.onlookup [as oncompletel(node:dns:110:8)
下面是我的代码:

//Imports
const fs = require('fs');
const net = require('net');
const path = require('node:path');
const { app, ipcMain, BrowserWindow } = require('electron');

//general variables
let settings
let mainWindow
const isMac = process.platform === 'darwin';

//create the server
let server

//window cunstructor
const createWindow = () => {
    mainWindow = new BrowserWindow({
        title: 'Bitburner Dashboard',
        width: 800,
        height: 600,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: true,
            preload: path.join(__dirname, 'preload.js')
        }
    });

    mainWindow.loadFile('front/index.html');
}

//wait for window to start server
ipcMain.on('mainWindow-ready', () => {
    if (!fs.existsSync(path.join(__dirname, 'settings.json'))) {
        fs.writeFileSync(path.join(__dirname, 'settings.json'), JSON.stringify({
            port: 5555
        }), (error) => {
            if (error) {
                console.log(error)
            }
            throw error;
        })
    }

    try {
        // reading a JSON file synchronously
        settings = JSON.parse(fs.readFileSync("settings.json"));
        console.log(settings)
    } catch (error) {
        // logging the error
        console.error(error);
        throw error;
    }

    server = net.createServer(socket => {

        //connect on port
        socket.connect(settings.port);
        socket.setKeepAlive(true);
    
        //format data and send on recieve
        socket.on("data", data => {
            data = data.toString().split("\n")[17].split(",");
    
            data = {
                id: data[0],
                state: data[1],
                updated_at: data[2],
                hostname: data[3],
                admin: data[4],
                level: data[5],
                purchased: data[6],
                connected: data[7],
                backdoored: data[8],
                cores: data[9],
                ram: {
                    used: data[10],
                    max: data[11],
                    free: data[12],
                    trueMax: data[13]
                },
                power: data[14],
                organisation: data[15],
                isHome: data[16],
                ports: {
                    required: data[17],
                    open: data[18],
                    ftp: data[19],
                    http: data[20],
                    smtp: data[21],
                    sql: data[22],
                    ssh: data[23]
                },
                security: {
                    level: data[24],
                    min: data[25]
                },
                money: {
                    available: data[26],
                    max: data[27],
                    growth: data[28]
                }
            };
    
            mainWindow.webContents.send("data-recieved", data);
    
            socket.destroy();
        });
    });

    mainWindow.webContents.send("settings-init", settings);
    server.listen(settings.port)
});

ipcMain.on('setting-update', (e, settings) => {
    server.close()
    server = net.createServer(socket => {

        //connect on port
        socket.connect(settings.port);
        socket.setKeepAlive(true);
    
        //format data and send on recieve
        socket.on("data", data => {
            data = data.toString().split("\n")[17].split(",");
    
            data = {
                id: data[0],
                state: data[1],
                updated_at: data[2],
                hostname: data[3],
                admin: data[4],
                level: data[5],
                purchased: data[6],
                connected: data[7],
                backdoored: data[8],
                cores: data[9],
                ram: {
                    used: data[10],
                    max: data[11],
                    free: data[12],
                    trueMax: data[13]
                },
                power: data[14],
                organisation: data[15],
                isHome: data[16],
                ports: {
                    required: data[17],
                    open: data[18],
                    ftp: data[19],
                    http: data[20],
                    smtp: data[21],
                    sql: data[22],
                    ssh: data[23]
                },
                security: {
                    level: data[24],
                    min: data[25]
                },
                money: {
                    available: data[26],
                    max: data[27],
                    growth: data[28]
                }
            };
    
            mainWindow.webContents.send("data-recieved", data);
    
            socket.destroy();
        });
    });
    server.listen(settings.port)
    console.log(JSON.stringify(settings))
    fs.writeFileSync(path.join(__dirname, 'settings.json'), JSON.stringify(settings), (error) => {
        if (error) {
            console.log(error)
        }
        throw error;
    })
})

//start app
app.on('ready', () => {
    createWindow();

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });
});

//close app
app.on('window-all-closed', () => {
    if (!isMac) app.quit();
})

app.on('close', () => {
    server.close()
});

字符串
我试过关闭服务器,但这不是问题所在。

sg2wtvxw

sg2wtvxw1#

我发现了问题所在:我基本上是在TCP服务器上发送HTTP请求。我通过修改服务器代码来解决这个问题:

let server = net.createServer(conn => {
    conn.on('data', data => {
        conn.write(data + '\r\n');
        mainWindow.webContents.send("data-recieved", JSON.parse(data.toString().split('\n')[17]));
    });

    conn.on('end', () => {
    });
});

字符串
完整的代码看起来像这样:

/* --------------------------------- Imports -------------------------------- */
const fs = require('fs');
const net = require('net');
const path = require('node:path');
const { app, ipcMain, BrowserWindow } = require('electron');



/* -------------------------------- variables ------------------------------- */
let settings;
let mainWindow;
const isMac = process.platform === 'darwin';



/* --------------------------------- server --------------------------------- */
let server = net.createServer(conn => {

    conn.on('data', data => {
        conn.write(data + '\r\n');
    
            mainWindow.webContents.send("data-recieved", JSON.parse(data.toString().split('\n')[17]));
    });

    conn.on('end', () => {
    });
});

/* --------------------------- window constructor --------------------------- */
const createWindow = () => {
    mainWindow = new BrowserWindow({
        title: 'Bitburner Dashboard',
        width: 800,
        height: 600,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: true,
            preload: path.join(__dirname, 'preload.js')
        }
    });

    mainWindow.loadFile('front/index.html');
}

/* ----------------------------------- IPC ---------------------------------- */
//wait for window to start server
ipcMain.on('mainWindow-ready', () => {
    //open settings
    openSettings();

    mainWindow.webContents.send("settings-init", settings);
    server.listen(settings.port)
});

ipcMain.on('setting-update', (e, settings) => {

    //close the server and start on the good port
    server.close()
    server.listen(settings.port)

    //save the settings
    fs.writeFileSync(path.join(__dirname, 'settings.json'), JSON.stringify(settings), (error) => {
        if (error) {
            console.log(error)
        }
        throw error;
    })
})

/* -------------------------------- Funcntions ------------------------------- */
//open the setting file or create one
function openSettings() {

    //Check if the file exists
    if (!fs.existsSync(path.join(__dirname, 'settings.json'))) {

        //creates the file if it does not exist
        fs.writeFileSync(path.join(__dirname, 'settings.json'), JSON.stringify({
            port: 5000
        }), (error) => {
            if (error) {
                console.error(error);
            }
            throw error;
        });

        settings = {
            port: 5000
        };
    } else {

        //Opens the file
        try {
            // reading a JSON file synchronously
            settings = JSON.parse(fs.readFileSync("settings.json"));
        } catch (error) {
            if (error) {
                console.error(error);
            }
            throw error;
        }
    }
}



/* ------------------------------- app routes ------------------------------- */
//start app
app.on('ready', () => {
    createWindow();

    //kill server when closing window
    mainWindow.on('close', () => {
        server.close();
    })

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });
});

//make sure server is close on close
app.on('close', () => {
    server.close();
});

//close app
app.on('window-all-closed', () => {
    if (!isMac) app.quit();
})

相关问题