我可以将渡槽连接到封闭的网络套接字(侦听器并获取数据)问题是我无法返回新的Response.ok。它显示为空...
我正在使用Aqueduct 3.0。大多数文档看起来像片段。我很难使用飞镖插座。但是现在我可以从套接字获取文本了,而且无法从渡槽Web API通过Internet发送数据。
class LoginController extends Controller {
String _xCustomerToken;
String _xCustomerName;
var list = [];
@override
Future handle(Request request) async {
String reply;
Socket.connect('192.168.1.22’, 1024).then((socket) async {
socket.listen((data) async {
reply = await new String.fromCharCodes(data).trim();
print("reply: $reply");
var list = reply.split(":_:");
print(list);
_xCustomerToken = list[2];
_xCustomerName = list[3];
// CAN PRINT THE SOCKET DATA
// EXAMPLE: ”Customer Token: 998877, CustomerName: NIYAZI TOROS”
print(
"Customer Token: $_xCustomerToken, CustomerName: $_xCustomerName");
await new Future.delayed(new Duration(seconds: 2));
}, onDone: () {
print("Done");
});
socket.write('Q101:_:49785:_:x\r\n');
});
// CANT RETURN THE SOCKET DATA
return new Response.ok(
// EXAMPLE: "Customer Token: null, CustomerName: null”
"Customer Token: $_xCustomerToken, CustomerName: $_xCustomerName");
}
}
更新: 我将return语句放入其中以等待(侦听),现在键入http://192.168.1.22:8888/login即可正确获取信息。
class LoginController extends Controller {
String _xCustomerToken;
String _xCustomerName;
String _xResult;
var list = [];
@override
Future<RequestOrResponse> handle(Request request) async {
String reply;
var socket = await Socket.connect('192.168.1.22', 1024);
socket.write('Q101:_:49785:_:x\r\n');
await for (var data in socket) {
reply = await new String.fromCharCodes(data).trim();
var list = reply.split(":_:");
_xCustomerToken = list[2];
_xCustomerName = list[3];
_xResult = "$_xCustomerToken:_:$_xCustomerName";
print("$_xResult");
return new Response.ok("$_xResult");
}
return new Response.ok("No data");
}
}
答案 0 :(得分:1)
.listen()
不会等待完成以执行其余代码,然后您将在return new Response.ok("Customer Token: $_xCustomerToken, CustomerName: $_xCustomerName");
右下角输入空值。您可以尝试使用await代替:
class LoginController extends Controller {
String _xCustomerToken;
String _xCustomerName;
var list = [];
@override
Future handle(Request request) async {
String reply;
var socket = await Socket.connect('192.168.1.22’, 1024);
socket.write('Q101:_:49785:_:x\r\n');
await for (var data in socket) {
reply = await new String.fromCharCodes(data).trim();
print("reply: $reply");
var list = reply.split(":_:");
print(list);
_xCustomerToken = list[2];
_xCustomerName = list[3];
// CAN PRINT THE SOCKET DATA
// EXAMPLE: ”Customer Token: 998877, CustomerName: NIYAZI TOROS”
print("Customer Token: $_xCustomerToken, CustomerName: $_xCustomerName");
await new Future.delayed(new Duration(seconds: 2));
}
return new Response.ok("Customer Token: $_xCustomerToken, CustomerName: $_xCustomerName");
}
}