我在Dart中重新创建一些JavaScript代码。
代码使用TCP创建与智能设备的连接,发送数据并侦听响应。
JavaScript代码
var socket = net.connect(port, ip);
socket.write(Buffer.from(data, 'hex'));
socket.once('data', (data) => {
console.log(data);
});
我的Dart代码
/// Creating a socket with the device ip and port
Socket socket = await Socket.connect(ip, port);
/// Send data to the device
socket.write(data);
/// Getting first response synchronicly
Uint8List dataFromDevice = await socket.first;
print(dataFromDevice);
由于某些原因,我从来没有收到智能设备的任何响应。
没有错误,套接字对象有已连接的属性。我怀疑数据根本没有被发送。
您可以通过将socket.write(data);
更改为socket.add(data);
来解决这个问题。
/// Creating a socket with the device ip and port
Socket socket = await Socket.connect(ip, port);
/// Send data to the device
socket.add(data);
/// Getting first response synchronicly
Uint8List dataFromDevice = await socket.first;
print(dataFromDevice);
我有假设至于为什么会这样。
.write
在dart中不知道如何像JavaScript.write
那样处理数组。
对于传输字节列表,我们使用.add
函数。