【问题标题】:continuously passing events from main to renderer process不断地将事件从主进程传递到渲染器进程
【发布时间】:2017-01-22 09:20:46
【问题描述】:

我一直在使用 Electrons 同步和异步 RPC 通信机制,并且可以很好地在进程之间传递我的数据。但是,我现在需要不断地将事件数据(有点像聊天应用程序)发送到渲染器进程并更新一些文本。

这在电子中可能吗?我猜我需要在渲染器进程中创建某种监听器。

【问题讨论】:

    标签: ipc main electron renderer


    【解决方案1】:

    看起来确实如此。例如

    主进程:

    const ipc = require('electron').ipcMain
    
    ipc.on('asynchronous-message', function (event, arg) {
    event.sender.send('asynchronous-reply', 'pong')
    
    function countdown( elementName, minutes, seconds )
    {
    var element, endTime, hours, mins, msLeft, time;
    
    function twoDigits( n )
    {
      return (n <= 9 ? "0" + n : n);
    }
    
    function updateTimer()
    {
      msLeft = endTime - (+new Date);
      if ( msLeft < 1000 ) {
        //element.innerHTML = "countdown's over!";
        event.sender.send('asynchronous-reply', 'countdown is over')
      } else {
        time = new Date( msLeft );
        hours = time.getUTCHours();
        mins = time.getUTCMinutes();
        // element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() );
        event.sender.send('asynchronous-reply', (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() ));
        setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
      }
    }
    
    // element = document.getElementById( elementName );
    endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
    updateTimer();
    }
    countdown( "countdown", 1, 5 );
    })
    

    渲染进程:

     const {ipcRenderer} = require('electron')
    
     ipcRenderer.on('asynchronous-reply', (event, arg) => {
     // arg contain your message (example message...)
     })
     ipcRenderer.send('asynchronous-message', 'example example send to main process')
    

    【讨论】:

      【解决方案2】:

      您可以使用ipcMainipcRenderer

      在主进程中。

      const {ipcMain} = require('electron')
      ipcMain.on('asynchronous-message', (event, arg) => {
        event.sender.send('asynchronous-reply', 'example message...')
      })
      

      在渲染器进程中(网页)。

      const {ipcRenderer} = require('electron')
      
      ipcRenderer.on('asynchronous-reply', (event, arg) => {
        // arg contain your message (example message...)
      })
      ipcRenderer.send('asynchronous-message', 'example example send to main process')
      

      你也可以传递任何对象。

      【讨论】:

      • 谢谢。只要主进程正在发送它们,这是否会不断接收渲染器进程中的事件?
      • 像一个流?
      • 是的 - 这正是我的意思。
      • 抱歉,我不知道。我需要检查文档。
      猜你喜欢
      • 2016-11-15
      • 2019-12-29
      • 2018-05-29
      • 2018-01-05
      • 2017-06-01
      • 2022-01-11
      • 2017-05-01
      • 2022-01-15
      • 1970-01-01
      相关资源
      最近更新 更多