代码在这里:
try {
final InternetAddress targetAddress = InternetAddress("255.255.255.255");
_udpSocket.send(utf8.encode("hello"), targetAddress, 8889);
} on SocketException catch (e) {
print("on");
} catch (e, r) {
print("catch");
} finally {
print("hahah");
}
}
我想抓住这个例外然而,它没有捕捉到异常并在控制台中引发异常日志:
[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: SocketException: Send failed (OS Error: Can't assign requested address, errno = 49), address = 0.0.0.0, port = 8889
#0 _NativeSocket.send (dart:io-patch/socket_patch.dart:1205:34)
#1 _RawDatagramSocket.send (dart:io-patch/socket_patch.dart:2438:15)
#2 ConnectionManager._sendDetectDevicesDataPocket (package:drop/sdk/connection_manager.dart:98:16)
#3 ConnectionManager.startDetectingDevices (package:drop/sdk/connection_manager.dart:77:5)
<asynchronous suspension>
那么,我如何才能捕捉到这个异常???
Flutter医生:
[✓] Flutter (Channel stable, 2.8.1, on macOS 12.2 21D5025f darwin-x64, locale
zh-Hans-CN)
[!] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
✗ cmdline-tools component is missing
Run `path/to/sdkmanager --install "cmdline-tools;latest"`
See https://developer.android.com/studio/command-line for more details.
✗ Android license status unknown.
Run `flutter doctor --android-licenses` to accept the SDK licenses.
See https://flutter.dev/docs/get-started/install/macos#android-setup for
more details.
[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2020.3)
[☠] IntelliJ IDEA Ultimate Edition (the doctor check crashed)
✗ Due to an error, the doctor check did not complete. If the error message
below is not helpful, please let us know about this issue at
https://github.com/flutter/flutter/issues.
✗ FormatException: Unexpected extension byte (at offset 5)
[✓] VS Code (version 1.62.2)
[✓] Connected device (3 available)
我找到了原因。我用来发送数据的RawDatagramSocket
是我绑定以侦听数据的udp。当我创建一个新的RawDatagramSocket
来发送数据时,SocketException
已经不见了。
// error
_udpSocket =
await RawDatagramSocket.bind(InternetAddress.anyIPv4, _multicastPort, reuseAddress: true, reusePort: true);
_udpSocket.broadcastEnabled = true;
_udpSocket.listen((event) {
xxxxxx
})
_udpSocket.send()
/// works fine when create a new udp
_udpSocket =
await RawDatagramSocket.bind(InternetAddress.anyIPv4, _multicastPort, reuseAddress: true, reusePort: true);
_udpSocket.broadcastEnabled = true;
_udpSocket.listen((event) {})
final RawDatagramSocket udp = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);
udp.broadcastEnabled = true;
udp.send(utf8.encode(modelJson), _hotpotAddress, _multicastPort);
udp.close()
这对我有效:
import 'dart:io';
...
try {
final result = await InternetAddress.lookup('example.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
print('connected');
}
} on SocketException catch (_) {
print('not connected');
}