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:
- Future Starts Here
- Request: "Hello World”
- Request has data Socket sends data to database
- (6) null. --- expected return "Welcome Sir/Madam"
- Future Ends Here
- Print_test: null --- expected return "Welcome Sir/Madam"
- Socket start to listen to database
- (1) "Welcome Sir/Madam”