sockets - 无法捕获 SocketException

标签 sockets exception dart socketexception

我正在尝试 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/

相关文章:

java - If 语句中的空指针异常

c# - 主服务器宕机

dart - Http响应状态码常量

firebase - 我如何使用从其他页面获取的值

c# - MSTest 单元测试断言特定的异常消息

webview - 为什么 initState 在 WebView 上的 url 更改后不起作用?

php - 当使用 netcat 作为客户端发送文件或管道输出时,如何避免 netcat 阻塞?

c - 什么操作导致 select 函数在检测套接字的写入状态时超时。

c++ - C++ `recv` 函数如何处理数据接收?它能收到部分 "packet"吗?

angular - 是什么决定了Socket IO的Angular区域