connectTo method
The client can connect to the Server that is already listening for connection.
ipAddress
is the IP to use in connecting to the server if the default detected
one is not the interface you want to use.
ipAddress
is not validated for correctness or if really it is owned by this Device
All IP addresses for host can be obtained using the ipAddresses property
Implementation
void connectTo(Device device, {String ipAddress}) async{
// Disconnect from Server if we have already previously connected
await _disconnectFromServer();
// Use the detected IP address to connect to the server
try {
// TODO we need to figure out how to set the connecting interface to bind to.
// This can be an issue if a different interface is being used to make the
// request. A SocketException will be thrown due to failing with timeout
_socket = await Socket.connect(device.ip, device.port,
sourceAddress: ipAddress ?? _ipAddress);
}
catch(error, stackTrace){
_connectionListener?.onDisconnected(device, true, error, stackTrace);
disconnect();
return;
}
_connected = true;
device._isConnected = true;
device._socket = _socket;
// fire connection listener
_connectionListener?.onConnected(device);
_socket.listen((event) {
_connectionListener?.onMessage(Packet.fromBytes(event), device);
}, onDone: () async{
await disconnect(); // disconnect from everything
// fire disconnection listener
_connectionListener?.onDisconnected(device, false, null, null);
}, onError: (Object error, StackTrace stackTrace) async{
await disconnect(); // disconnect from everything
// fire disconnection listener
_connectionListener?.onDisconnected(device, true, error, stackTrace);
}, cancelOnError: true);
}