我正在编写一个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')
`
答案 0 :(得分: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)
};