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