如何向/从javascript web worker传递二进制消息?

时间:2021-05-05 09:51:15

I'm building a multi-threaded client side javascript application, and I would like to have a background thread pull binary data and pass it to the main thread. I know this can be done in other languages via serialization, but how do I accomplish this in javascript?

我正在构建一个多线程客户端javascript应用程序,我想有一个后台线程拉二进制数据并将其传递给主线程。我知道这可以通过序列化在其他语言中完成,但我如何在javascript中完成此操作?


I might turn this application into a standalone XULrunner application down the line for even more efficiency, so I'd rather go the HTML5 "web workers" route versus using Gears.

我可能会将这个应用程序变成一个独立的XULrunner应用程序,以提高效率,所以我宁愿选择HTML5“web worker”路由而不是使用Gears。

3 个解决方案

#1


The Web Workers postMessage API takes a JavaScript object. The Mozilla Using web workers documentations says:

Web Workers postMessage API采用JavaScript对象。 Mozilla使用网络工作者文档说:

You can safely pass objects in and out of workers using the postMessage() method; objects are automatically converted to JSON internally.

您可以使用postMessage()方法安全地将对象传入和传出工作组;对象在内部自动转换为JSON。

So, you can use any JavaScript object that supports or can be converted to your binary data. Depending on other factors, maybe convert to a Base64 string (see How can you encode to Base64 using Javascript?) or use an array on numbers.

因此,您可以使用任何支持或可以转换为二进制数据的JavaScript对象。根据其他因素,可能会转换为Base64字符串(请参阅如何使用Javascript编码为Base64?)或在数字上使用数组。

#2


You use postMessage as was otherwise indicated here, however, the object / data must be base64 encoded before being passed using atob()

您使用postMessage,如此处另有说明,但是,在使用atob()传递之前,对象/数据必须是base64编码的

#3


Are you open to using Google Gears? This is exactly the kind of thing their WorkerPool threading implementation is for.

您是否愿意使用Google Gears?这正是他们的WorkerPool线程实现的目的。

#1


The Web Workers postMessage API takes a JavaScript object. The Mozilla Using web workers documentations says:

Web Workers postMessage API采用JavaScript对象。 Mozilla使用网络工作者文档说:

You can safely pass objects in and out of workers using the postMessage() method; objects are automatically converted to JSON internally.

您可以使用postMessage()方法安全地将对象传入和传出工作组;对象在内部自动转换为JSON。

So, you can use any JavaScript object that supports or can be converted to your binary data. Depending on other factors, maybe convert to a Base64 string (see How can you encode to Base64 using Javascript?) or use an array on numbers.

因此,您可以使用任何支持或可以转换为二进制数据的JavaScript对象。根据其他因素,可能会转换为Base64字符串(请参阅如何使用Javascript编码为Base64?)或在数字上使用数组。

#2


You use postMessage as was otherwise indicated here, however, the object / data must be base64 encoded before being passed using atob()

您使用postMessage,如此处另有说明,但是,在使用atob()传递之前,对象/数据必须是base64编码的

#3


Are you open to using Google Gears? This is exactly the kind of thing their WorkerPool threading implementation is for.

您是否愿意使用Google Gears?这正是他们的WorkerPool线程实现的目的。