How to return socket data from Future in Dart?

2019-08-01 06:12发布

Likely I send data to server and get data back even very big data using code below between =========== lines. This was to my experiment for I need to some intermediate solution so I can connect my Flutter app to tcp socket. For this I choose auqeduct.io. Today help from Gazi I found the solution to complete my code between =========== lines.

Because of I am using auqeduct their handle function look like this.

@override
  Future<RequestOrResponse> handle(Request request) async {

So, I try to modify my code and use Future to return socket data as string. I can get data using code below between =========== lines, but I cannot get any data using Future _handle(String _request) async.

_socket.listen((data) prints the data cannot assign data to string, so I cannot return string.

works: print("(1) $_secureResponse");

not worked: _secureResponse = new String.fromCharCodes(data).trim();

If I don't use Future and put the code inside main() all is working perfectly.

In my test server I send a "Hello World" and in return I get "Welcome Sir/Madam".

My question is: How to return socket data from Future in Dart?

import 'dart:async';
import 'dart:io';
import 'dart:convert';

Socket socket;
String _errorData;
String _secureResponse;

void main() async {

  var _test = await _handle(“Hello World”);
  print("Print _test: $_test");

}


Future<String> _handle(String _request) async {
  print("Future Starts Here");
  print("Request: $_request");
    _errorData = "Server_Error";
    if (_request != null) {
      print("Request has data");
      // =============================================================
      Socket _socket;
      await Socket.connect("192.168.22.120”, 3000).then((Socket sock) {
        _socket = sock;
        _socket.listen((data) {
          print("Socket start to listen to database");
          // GET FROM SERVER *********************
          _secureResponse =  new String.fromCharCodes(data).trim();
          print("(1) $_secureResponse");
        }, onError: ((error, StackTrace trace) {
          _secureResponse = _errorData;
          print("(2) $_secureResponse");
        }), onDone: ((){
          _socket.destroy();
          exit(0);
        }), cancelOnError: false);
      }).then((_) {
        print("Socket sends data to database");
        // SENT TO SERVER ************************
        _socket.write('$_request\r\n');
      }).catchError((AsyncError e) {
        _secureResponse = _errorData;
        print("(3) $_secureResponse");
        exit(1);
      });
      // ==============================================================
    } else {
      _secureResponse = _errorData;
      print("(4) $_secureResponse");
    }
  print("(6) $_secureResponse");
  print("Future Ends Here");
  return _secureResponse;
}

Result:

  1. Future Starts Here
  2. Request: "Hello World
  3. Request has data Socket sends data to database
  4. (6) null. --- expected return "Welcome Sir/Madam"
  5. Future Ends Here
  6. Print_test: null --- expected return "Welcome Sir/Madam"
  7. Socket start to listen to database
  8. (1) "Welcome Sir/Madam

1条回答
爷的心禁止访问
2楼-- · 2019-08-01 06:17

This might work. I think you should read up about streams/futures/async/await, though.

Future<String> _handle(String _request) async {
  print("Future Starts Here");
  print("Request: $_request");
    _errorData = "Server_Error";
    if (_request != null) {
      print("Request has data");
      // =============================================================
      Socket _socket;
      await Socket.connect("192.168.22.120”, 3000).then((Socket sock) {
        _socket = sock;
      }).then((_) {
        print("Socket sends data to database");
        // SENT TO SERVER ************************
        _socket.write('$_request\r\n');
        return _socket.first;
      }).then((data) {
        print("Socket start to listen to database");
        // GET FROM SERVER *********************
        _secureResponse =  new String.fromCharCodes(data).trim();
        print("(1) $_secureResponse");
      }).catchError((AsyncError e) {
        _secureResponse = _errorData;
        print("(3) $_secureResponse");
        exit(1);
      });
      // ==============================================================
    } else {
      _secureResponse = _errorData;
      print("(4) $_secureResponse");
    }
  print("(6) $_secureResponse");
  print("Future Ends Here");
  return _secureResponse;
} 
查看更多
登录 后发表回答