如何将Dart Html客户端Web套接字响应从Blob转换为Uint8List? [英] How to convert a Dart Html client web socket response from Blob to Uint8List?
问题描述
我已经实现了自己的二进制消息协议,用于从Dart客户端到Java服务器的简单请求/响应对象.这些在Dart中编码为Uint8List,在Java的远程服务器上编码为ByteBuffer.往返行程适用于[dart:io]中的WebSocket,因为Dart客户端命令应用程序中的websocket.listen流处理程序将传递类型为Uint8List的数据.
I’ve implemented my own binary message protocol for simple request/response objects from a Dart client to a Java server. These are encoded in Dart as an Uint8List and on the remote server in Java as a ByteBuffer. The round trip works for the WebSocket in [dart:io] because the websocket.listen stream handler in the Dart client command app is passed data typed as Uint8List.
在[dart:html]中,从websocket.onMessage流接收到的MessageEvent.data中的响应数据被键入为Blob.我找不到将Blob转换为Uint8List的方法.因为响应通常是一个大型的二进制数字数组(双精度),它将为虚拟滚动上下文提供数据,所以我想尽量减少复制.有人可以指出我正确的方向.
In [dart:html] the response data in MessageEvent.data received from the websocket.onMessage stream is typed as Blob. I’m not finding a way to convert the Blob to Uint8List. Because the response will often be a large binary array of numbers (double) that will be supplying data to a virtual scrolling context, I want to minimize copying. Could someone please point me in the right direction.
推荐答案
According to this article, you need to use a FileReader to do this.
此示例似乎有效,当我在Chrome中测试该结果时,结果类型为Uint8List.
This example seems to work, the result type is a Uint8List when I tested this in Chrome.
var blob = new Blob(['abc']);
var r = new FileReader();
r.readAsArrayBuffer(blob);
r.onLoadEnd.listen((e) {
var data = r.result;
print(data.runtimeType);
});
另一种选择是将 WebSocket.binaryType 设置为"arraybuffer".然后,MessageEvent.data将返回一个ByteBuffer,可以将其转换为Uint8List.请参见下面的示例.
Another option is to set WebSocket.binaryType to "arraybuffer". Then MessageEvent.data will return a ByteBuffer which can be turned into a Uint8List. See the example below.
import 'dart:html';
import 'dart:typed_data';
void main() {
var ws = new WebSocket('...')..binaryType = 'arraybuffer';
ws.onMessage.listen((MessageEvent e) {
ByteBuffer buf = e.data;
var data = buf.asUint8List();
// ...
});
}
这篇关于如何将Dart Html客户端Web套接字响应从Blob转换为Uint8List?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!