簡體   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