1

我正在编写一个 nodejs 脚本。我使用worker_threads 和BroadcastChannel 创建了一个worker。我无法将消息从我的主线程发送到工作线程。但是,我可以将消息从 Worker 发送到主线程。

以下是我的 main.js 代码

 let worker = new Worker('worker.js')
 let channel = new BroadcastChannel('testChannel', { 
   type: 'node', 
   webWorkerSupport: true
 })

 channel.postMessage('sending message to worker')

 channel.onmessage  =  message =>  {
 console.log('received message in channel main')
   console.log(message)
 }  

以下是 worker.js 中的代码

 let channel = new BroadcastChannel('testChannel', {
   type: 'node', 
   webWorkerSupport: true
 })

 channel.onmessage = message => {
   console.log('received message in channel')
   console.log(message)
 }

 channel.postMessage('from worker')
`
4

1 回答 1

0

您将需要BroadcastChannel为传入消息添加另一个对象。

示例(main.js):

let broadcastingChannel = new BroadcastChannel('testChannel', { 
    type: 'node', 
    webWorkerSupport: true
});

broadcastingChannel.postMessage('sending message to worker')


let incomingChannel = new BroadcastChannel('testChannel', { 
    type: 'node', 
    webWorkerSupport: true
});

incomingChannel.onmessage = message => {
    console.log('received message in channel main')
    console.log(message)
};
于 2019-02-28T12:45:40.117 回答