我可以在渡槽响应控制器中调用任何dart函数吗?

时间:2019-02-04 09:17:05

标签: dart aqueduct

我需要调用dart函数做一些事情并将数据返回给渡槽控制器。那么,我可以在渡槽响应控制器中调用任何dart函数吗?如果是,怎么办?

class NtmsApiController extends Controller {
 @override
 Future<RequestOrResponse> handle(Request request) async {
   try {
           if (request.path.remainingPath != null) {
          _requestValue = request.path.remainingPath;
         …
         … can I go from here to dart function and get data back???? If yes, how?

更新代码: 我有全局变量,它以null打印。套接字获取数据后,void _printResponse(String _response)打印数据,然后从那里将数据分配给全局变量。但是在Future句柄中,数据变为空,因此我不能将其作为响应对象返回。有想法吗?

@override
Future<RequestOrResponse> handle(Request request) async {
  _stopWatch = Stopwatch() //Global
    ..start();
  _response = ""; // Global

  if (request.path.remainingPath != null) {
    final _requestValue = request.path.remainingPath;

    await _getData(_requestValue);
  }

  print(_secureResponse); // It prints null, _secureResponse is Global variable
  return Response.ok("$_secureResponse")
    ..contentType = ContentType.json;
}

//TODO: GET DATA FROM CSBINS
Future<Null> _getData(String _request) async {
  await Socket.connect("192.168.22.120", 3000).then((Socket sock) {
    _socket = sock;
    _socket.write('$_request\r\n');
    _socket.listen (dataHandler,
            onError: errorHandler,
            onDone: doneHandler,
            cancelOnError: true);
  }).catchError((AsyncError e) {
    _response = "Server_Error";
  });

}

void dataHandler(data) {
  final List<int> byteArray = data;
  _response =  String.fromCharCodes(byteArray).trim();
}

void errorHandler(error, StackTrace trace) {
  _response = "Server_Error";
}

void doneHandler() {
  _socket.destroy();
}

void _printResponse(String _response) {

  // prints succefully ***************************
  print("$_response ... (${_stopWatch.elapsedMilliseconds} ms)");

  _secureResponse = _response;
  _stopWatch..stop();
  if (_stopWatch.isRunning == false) {
    _socket.flush();
    _socket.close();
    print("Socket Closed.");
  }
}

0 个答案:

没有答案