1

I am writing a nodejs script. In that I have created a worker using worker_threads and a BroadcastChannel. I am not able to send message from my main thread to worker threads. However, I am able to send message from Worker to main thread.

Following is my code for 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)
 }  

Following is the code in 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')
`
Anusha Bhat
  • 99
  • 1
  • 12

1 Answers1

0

You will need to add another BroadcastChannel object for incoming messages.

Example (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)
};
Shahar Shokrani
  • 7,598
  • 9
  • 48
  • 91
  • Why do I need to add another BroadcastChannel? It is mentioned in the doc to create a channel with a name and use the same name while receving. Ref https://github.com/pubkey/broadcast-channel – Anusha Bhat Feb 28 '19 at 12:49
  • One for receive and one for broadcast – Shahar Shokrani Feb 28 '19 at 12:51
  • That's what I have done already. If you see code in main.js, there is a broadcast channel defined and an in worker.js, there is channel defined. Are you suggesting in main.js, I have to define 2 broadcast channels - one for receiving and one for sending and same in worker.js? – Anusha Bhat Feb 28 '19 at 12:55
  • Yes. see edited answer. let me know if any other problem regarding this issue. – Shahar Shokrani Feb 28 '19 at 12:58
  • Thanks for the answer. However, what you have mentioned applies for javascript. Since, I am writing a node script, it is not necessary. I got the solution from here. https://github.com/pubkey/broadcast-channel/issues/14#issuecomment-468350570 – Anusha Bhat Mar 12 '19 at 11:26