Mal*_*dus 6 sockets encoding byte dart flutter
我被困在我能想到的最愚蠢的障碍上。我正在开发一个 flutter 应用程序,它应该通过 TCP 套接字(在本地 wifi 网络上)发送一个字节数组。
所述字节是原始的,不代表任何编码中有意义的字符(我有 0xFF 等值)。我的代码使用套接字write
方法成功连接和发送数据。不幸的是,该方法仅将编码String
作为参数,而从字符代码创建一个会破坏我的消息。
这是我的代码:
var message = Uint8List(4);
var bytedata = ByteData.view(message.buffer);
bytedata.setUint8(0, 0x01);
bytedata.setUint8(1, 0x07);
bytedata.setUint8(2, 0xFF);
bytedata.setUint8(3, 0x88);
socket.write(String.fromCharCodes(message))
Run Code Online (Sandbox Code Playgroud)
当 0x01 和 0x07 被正确接收时,0xFF 和 0x88 被转换成几个其他字节,0xC3BF 和 0xC287(用netcat -l 8080 | hexdump
命令检查)。
我已经用谷歌搜索了一段时间,寻找一种发送原始字节而不将它们编码为字符串的方法,但找不到任何东西。难道根本就没有考虑过吗?我意识到 Flutter 和 Dart 是用于高级 Web 开发的,但在我看来这很荒谬。
Mal*_*dus 12
显然可以在不关心编码的情况下写入字节;然而,谷歌搜索并没有立即给出答案,可能是因为没有其他人提出过这个问题,而且函数本身没有明显的名称或描述。
在Socket
从达特继承类的IOSink
类,它有add()
那不正是我需要它的方法。
从文档:
void add (List<int> data)
Adds byte data to the target consumer, ignoring encoding.
The encoding does not apply to this method, and the data list is passed directly to the target consumer as a stream event.
This function must not be called when a stream is currently being added using addStream.
This operation is non-blocking. See flush or done for how to get any errors generated by this call.
The data list should not be modified after it has been passed to add.
Run Code Online (Sandbox Code Playgroud)
https://api.dartlang.org/stable/2.0.0/dart-io/Socket-class.html
正确的代码很简单
var message = Uint8List(4);
var bytedata = ByteData.view(message.buffer);
bytedata.setUint8(0, 0x01);
bytedata.setUint8(1, 0x07);
bytedata.setUint8(2, 0xFF);
bytedata.setUint8(3, 0x88);
socket.add(message)
Run Code Online (Sandbox Code Playgroud)