繁体   English   中英

与nodejs worker_threads模块一起使用时广播频道问题

[英]Issue with broadcast channel when using with nodejs worker_threads module

我正在编写一个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')
`

您将需要为传入消息添加另一个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)
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM