How to catch dart.io socket error?

17 views
Skip to first unread message

Niyazi Toros

unread,
Jul 5, 2018, 1:53:20 AM7/5/18
to Dart Web Development

Hi,

I am new to Dart, Aqueduct and socket. I am trying to learn all while I am working and making test project to understand. Any deep info and help appreciated.

Below code works for me as I expected in aqueduct. Problem is that I need to modify value before sending a socket, so I need to await like this. "await for (var data in socket)" Also I have some heavy work in 2 places. First I need to decrypt the request before sending to socket "socket.write('$tempData\r\n');".
Once I get a data from socket (listen) "await for (var data in socket)" I need to do some heavy work again before sending as response.

I had a 3 question that shown below.
Question-1: How to catch error if serevr is not reachable or down?
Question-2: How to catch error when trying send data to socket?
Question-3: How to catch error while socket listen returning data?


import 'package:aqueduct/aqueduct.dart';
import 'package:niyaziapi/niyaziapi.dart';
import 'package:niyaziapi/util/niyaziprivate.dart';

class LoginController extends Controller {
 
@override
 
Future<RequestOrResponse> processRequest(Request request) async {
 
if (request.path.variables.containsKey('value')) {
 
var _xPrivate = (request.path.variables['value']).trim();
 
var tempData = await getPrivate(_xPrivate);

 // TODO: Question-1: How to catch error if serevr is not reachable or down
 
var socket = await Socket.connect('192.168.1.22', 1024);
 
print("socket: $socket");

 // TODO: Question-2: How to catch error when trying send data to socket
 socket
.write('$tempData\r\n');

 // TODO: Question-3: How to catch error while socket listen (returning data)has error
 
await for (var data in socket) {
 
var reply = new String.fromCharCodes(data).trim();
 // Do some heavy work in here then
 
return new Response.ok("$reply");
 
}
 
} else {
 
return new Response.ok("wrong rquest");
 
}
 
}

 
Future<String> getPrivate(_xPrivate) async {
 // Do some heavy decryption in here then

 
return "data";
 
}
}

Reply all
Reply to author
Forward
0 new messages