connect method
Implementation
Future<bool> connect({
int port = 9100,
Duration? timeout = const Duration(seconds: 5),
bool canRetry = true,
bool throwError = false,
}) async {
port = addressPort;
if (_socket != null && _isConnect) {
return true;
}
_close();
try {
_socket = await Socket.connect(
address,
port,
sourcePort: _sourcePort ?? 0,
timeout: timeout,
);
_isConnect = true;
_sourcePort = _socket?.port;
_socketSubscription = _socket?.listen(
(event) {
//暂无处理
},
onDone: () {
_close();
},
onError: (e) {
_close();
},
);
} catch (e) {
_close();
if (canRetry) {
final isInUseException =
e.toString().contains('Address already in use');
if (isInUseException) {
//需要使用新的 sourcePort
_sourcePort = null;
}
return connect(
port: port,//port
timeout: timeout,
canRetry: false,
throwError: throwError,
);
} else {
if (throwError) {
rethrow;
}
}
}
return _isConnect;
}