gpt4 book ai didi

asynchronous - DART 异步/等待不等待

转载 作者:行者123 更新时间:2023-12-04 04:54:11 26 4
gpt4 key购买 nike

所以我一直在尝试使用 DART(我的核心语言是 C++,以及嵌入式 C 派生语言)。因此,我的代码可能并不漂亮,因为我更像是一名程序程序员,但我正在学习......我一直在努力解决与等待同步有关的 Futures,基本上,我根本无法获得 DART等待。以下代码建立与小型嵌入式设备的套接字连接并提取信息。一切正常,但请注意操作顺序应该是 main() 从控制台获取一些信息,然后调用方法 cardStatus 运行并通过套接字连接从嵌入式设备获取信息。这是等待应该发生的地方。当返回 Future 时,它​​应该转到 printstuff() 方法。我已经添加了应该按顺序阅读的打印语句:

  • 这应该打印第一个
  • 这应该打印第二个
  • 这应该打印第三

相反,由于 cardstatus 调用没有发生等待(这很耗时),我得到:

  • 这应该打印 1st
  • 这应该打印第三
  • 这应该打印 2

我已经关注了另一个关于异步使用的线程,并且似乎至少遵循了一种可靠的方式来使用这个 Other thread (我尝试了一个 .then 和一个具有类似结果的完成器,所以我觉得我缺少一些核心内容).. 但我已经坚持了一个星期了。

下面的代码以及控制台输出。

import 'dart:io';
import 'dart:async' show Future;

const String STATUS = "#111111;";

String defaultIP = "10.1.14.202";
int defaultConfigPort = 5111;
int defaultControlPort = 6722;

var card = new Map();

getInput(String defaults) {
String takenin = stdin.readLineSync();
if (takenin == '') takenin = defaults;
return takenin;
}

Future main() async {
stdout.write('What is the IP address of the card ($defaultIP): ');
String ipaddress = getInput(defaultIP);
defaultIP = ipaddress;
print ("This should print 1st");
stdout.writeln("Connecting to $defaultIP");
await cardStatus(defaultIP, defaultConfigPort, STATUS, card);
printstuff();
}

printstuff() {
stdout.writeln(card['subnet']);
print ("This should print 3rd");
}
Future cardStatus(String ip, int port, String message, Map card) {
return new Future.delayed(Duration.ZERO, () {
Socket.connect(ip, port).then((socket) {
print('Connected to: '
'${socket.remoteAddress.address}:${socket.remotePort}');

socket.listen((data) {
print(new String.fromCharCodes(data).trim());
List str1 = (new String.fromCharCodes(data).trim().split(','));
print(str1);
print ("This should print 2nd");
//var card = new Map();
card['ip'] = str1[0];
card['subnet'] = str1[1];
card['gateway'] = str1[2];
card['unknown'] = str1[3];
card['persist'] = str1[4] == 'true';
card['build'] = str1[5];
card['serial'] = str1[6].substring(0, 14);
card['cloudpassword'] = str1[6].substring(14, 20);
card['DNS'] = str1[7];
card['cloudhost'] = str1[8];
card['cloudenabled'] = str1[9] == 'true';
print(card['ip']);
},
onDone: () {
print("Done");
socket.destroy();
});

//Send the request
socket.write(message);
});
});
}

这是当前的控制台输出。请注意,如果 cardStatus 已完成,则 null 不应为 null,它将打印为 str1。

What is the IP address of the card (10.1.14.202): 
This should print 1st
Connecting to 10.1.14.202
null
This should print 3rd
Connected to: 10.1.14.202:5111
>10.1.14.202,255.255.255.0,10.1.14.1,,0,435,F44900A60040F8000000,192.168.1.1,connect.tutuuu.com,0;
[>10.1.14.202, 255.255.255.0, 10.1.14.1, , 0, 435, F44900A60040F8000000, 192.168.1.1, connect.tutuuu.com, 0;]
This should print 2nd
10.1.14.202
Done

Process finished with exit code 0

感谢大家的帮助!

最佳答案

您在 Socket.connect 之前缺少 return。就目前而言,您的代码刚刚开始连接,但永远不会等待它通过 future 。我强烈建议尽可能多地使用新的 await/async 语法。

这是一个获取谷歌主页的运行示例:

import 'dart:io';
import 'dart:async' show Future;

Future main() async {
print("This should print 1st");
await cardStatus('www.google.com', 80, 'GET /\nHTTP 1.1\n\n');
printstuff();
}

printstuff() {
print("This should print 3rd");
}

Future cardStatus(String ip, int port, String message) {
return new Future.delayed(Duration.ZERO, () {
return Socket.connect(ip, port).then((socket) {
print('Connected to: '
'${socket.remoteAddress.address}:${socket.remotePort}');

socket.listen((data) {
List str1 = (new String.fromCharCodes(data).trim().split(','));
print(str1.first);
print("This should print 2nd");
}, onDone: () {
print("Done");
socket.destroy();
}, onError: (e) {
print("Error while listening: $e");
});
socket.write(message);
});
});
}

下面是使用 await 和 try/catch 来处理错误的稍微编辑的版本:

import 'dart:io';
import 'dart:async' show Future;

Future main() async {
print("This should print 1st");
await cardStatus('www.google.com', 80, 'GET /\nHTTP 1.1\n\n');
print("This should print 3rd");
}

Future<String> cardStatus(String ip, int port, String message) async {
var socket = await Socket.connect(ip, port);
print('Connected to: '
'${socket.remoteAddress.address}:${socket.remotePort}');
socket.write(message);
print("Sent request");
try {
var response = await socket.fold(
'',
(String acc, List<int> data) =>
acc + new String.fromCharCodes(data).trim());
print("Received response: ${response.substring(0, 10)}");
return response;
} finally {
socket.close();
}
}

关于asynchronous - DART 异步/等待不等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44961460/

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