gpt4 book ai didi

dart - 有什么办法可以将数据从服务器发送到dart的客户端

转载 作者:行者123 更新时间:2023-12-03 03:43:52 25 4
gpt4 key购买 nike

我正在做客户端服务器应用程序(通过带有postgrelsql的浏览器)。我创建了服务器,它在一个端口上运行。如何从服务器到客户端获取数据。
客户端:

   req=new HttpRequest();
req.open('get', 'http://127.0.0.1:8082/');
var rr=req.send();
print(rr);

服务器端:
      HttpServer server = await HttpServer.bind('127.0.0.1', 8082);

await for (HttpRequest request in server) {
request.response.headers.add("Access-Control-Allow-Origin", "*");
request.response.headers.add("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT,OPTIONS");
request.response.write(await consoledatabaseconnection.someList());
handleRequest(request);
request.response.close();
}
void handleRequest(HttpRequest request) {
try {
if (request.method == 'GET') {
print('request get');

request.response.write('data form server');

} else {
print('request others');
}
} catch (e) {
print('Exception in handleRequest: $e');
}
print('Request handled.');
}

在服务器端如何返回数据。

最佳答案

服务器端代码

main(List<String> arguments) async {
HttpServer.bind('localhost', 8085).then((server) {
server.listen((HttpRequest request) {
request.response.headers.add("Access-Control-Allow-Origin", "*");
request.response.headers
.add("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT,OPTIONS");
request.response.headers.add('Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept,application/x-www-form-urlencoded');

if (request.method == "POST") {
List<int> dataBody = new List<int>();
request.listen(dataBody.addAll, onDone: () async {
query_dy = new String.fromCharCodes(dataBody);
request.response.write(await databaseconnection('your response code here'));
request.response.close();
});
}
});
});
}

客户端代码
req =新的HttpRequest();
req.open('post', 'http://localhost:8085');

req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

req.send('{"username": "$username","password": "$password"}');

req.onReadyStateChange.listen((_) {
if (req.readyState == HttpRequest.DONE &&
(req.status == 200 || req.status == 0)) {
//you can get response form server here
String responsefrmserver = req.responseText;

}
}
});

关于dart - 有什么办法可以将数据从服务器发送到dart的客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34629921/

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