gpt4 book ai didi

sockets - 无法捕获 SocketException

转载 作者:行者123 更新时间:2023-12-03 02:53:45 29 4
gpt4 key购买 nike

我正在尝试 Dart,我已经为此苦苦挣扎了很久。来电:

runServer() {
HttpServer.bind(InternetAddress.ANY_IP_V4, 8080)
.then((server) {
server.listen((HttpRequest request) {
request.response.write('Hello, World!');
request.response.close();
});
});
}

曾经像魅力一样工作。然后,尝试
try {
runServer();
} on Error catch (e) {
print("error");
} on Exception catch(f) {
print("exception");
}

现在我希望如果我使用这个 try-catch 并开始不止一次地监听同一个端口,因为我正在捕获所有异常和所有错误,程序不会崩溃。但是,在运行代码两次之后,我没有输入任何 try/catch 子句,而是得到:

Uncaut Error: SocketException: Failed to create server socket (OS Error: Only one usage of each socket address (protocol/network address/port) is normally permitted.



虽然我了解错误是什么,但我不明白为什么不简单地输入 catch Error/Exception 子句?

最佳答案

使用 try 无法捕获异步错误/catch ( https://www.dartlang.org/docs/tutorials/futures/ ) 至少除非你使用 async/await (https://www.dartlang.org/articles/await-async/)

另见 https://github.com/dart-lang/sdk/issues/24278

You can use the done future on the WebSocket object to get that error, e.g.:


import 'dart:async';
import 'dart:io';

main() async {
// Connect to a web socket.
WebSocket socket = await WebSocket.connect('ws://echo.websocket.org');

// Setup listening.
socket.listen((message) {
print('message: $message');
}, onError: (error) {
print('error: $error');
}, onDone: () {
print('socket closed.');
}, cancelOnError: true);

// Add message, and then an error.
socket.add('echo!');
socket.addError(new Exception('error!'));

// Wait for the socket to close.
try {
await socket.done;
print('WebSocket donw');
} catch (error) {
print('WebScoket done with error $error');
}
}

关于sockets - 无法捕获 SocketException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32810051/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com