【问题标题】:How to access the electron process from another npm process?如何从另一个 npm 进程访问电子进程?
【发布时间】:2020-12-19 01:44:41
【问题描述】:

我制作了一个脚本,它打开一个 tcp 服务器并监听传入的请求,然后创建一个 Windows 通知。代码如下:

const notifier = require('node-notifier');
const path = require('path');
const net = require('net');
const port = 7070;
const host = '';

const server = net.createServer();
server.listen(port, host, () => {
    console.log('TCP Server is running on port ' + port + '.');
});

let sockets = [];
server.on('connection', function(sock) {
    console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);
    sockets.push(sock);

    sock.on('data', function(data) {
        var tryCatch = true;
        try {
            JSON.parse(data);
        } catch (err) {
            tryCatch = err;
        }
        if (tryCatch == true) {
            var JSONdata = JSON.parse(data);
            if (JSONdata["action"] == "notification") {
                notifier.notify({
                        title: 'Recived Message',
                        message: JSONdata["message"],
                        icon: path.join(__dirname, 'icon.png'),
                        actions: ["OK", "Abbrechen"]
                    },
                    (err, data) => {
                        console.log('Waited');
                        console.log(JSON.stringify({ err, data }));
                        sock.write(JSON.stringify({ err, data }));
                        sock.write('\r');
                        sock.destroy();
                    }
                );
            } else if (JSONdata["action"] == "closeServer") {
                sock.destroy();
                server.close();
            }
        } else {
            sock.write(tryCatch.message);
            sock.destroy();
        }
    });

    // Add a 'close' event handler to this instance of socket
    sock.on('close', function(data) {
        let index = sockets.findIndex(function(o) {
            return o.remoteAddress === sock.remoteAddress && o.remotePort === sock.remotePort;
        })
        if (index !== -1) sockets.splice(index, 1);
        console.log('CLOSED: ' + sock.remoteAddress + ' ' + sock.remotePort);
        // server.close();
    });
});

该脚本可以正常运行。现在我想将它与我的电子应用程序连接起来。我想从这个 npm 进程访问电子应用程序,例如打开一个页面。但我不知道如何从外部和外部访问电子进程,我的意思是从另一个 npm 进程。希望有人可以帮助我或指出我正确的方向。我很感谢每一个答案或信息。

【问题讨论】:

  • 你的目的是什么?由于 Electron 的主要进程是 Node,因此您可以将这个服务器托管在 Electron 应用程序中。

标签: node.js npm tcp process electron


【解决方案1】:

说起来很简单。我没有找到有关如何访问另一个进程的解决方案,但是如果用户尝试打开另一个窗口,您可以只使用 vorbidd 或拦截和中断。然后,您可以改为生成自己的窗口并使用 ipcMain 和 ipcRender 模块将 smth 发送到所需的窗口。

【讨论】:

    猜你喜欢
    • 2011-02-10
    • 1970-01-01
    • 2016-08-11
    • 2018-06-09
    • 2018-06-12
    • 1970-01-01
    • 2013-04-13
    • 2015-08-21
    • 1970-01-01
    相关资源
    最近更新 更多