connect method

dynamic connect(
  1. int timeOut,
  2. Function callback, {
  3. int attempts = 1,
})

Initializes the connection. Socket starts listening to server for data 'callback' function will be called whenever data is received. The developer elaborates the message received however he wants No separator is used to split message into parts

  • @param timeOut the amount of time to attempt the connection in milliseconds
  • @param callback the function called when received a message. It must take a 'String' as param which is the message received
  • @param attempts the number of attempts before stop trying to connect. Default is 1.

Implementation

connect(int timeOut, Function callback,{int attempts=1}) async{

  int k=1;
  while(k<=attempts){
    try{
      _server = await Socket.connect(_ipAddress, _portAddress, timeout: new Duration(milliseconds: timeOut));
      break;
    }catch(ex){
      _printData(k.toString()+" attempt: Socket not connected (Timeout reached)");
      if(k==attempts){
        return;
      }
    }
    k++;
  }
  _connected=true;
  _printData("Socket successfully connected");
  _server!.listen((List<int> event) async {
    String received=(utf8.decode(event));
    _printData("Message received: "+received);
    callback(received);
  });
}