gpt4 book ai didi

javascript - 与 Node.js Worker_Threads 模块一起使用时出现广播 channel 问题

转载 作者:太空宇宙 更新时间:2023-11-04 01:34:44 27 4
gpt4 key购买 nike

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

关于javascript - 与 Node.js Worker_Threads 模块一起使用时出现广播 channel 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54925190/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com