首页 文章

如何在Dart中处理套接字断开连接?

提问于
浏览
7

我在服务器上使用Dart 1.8.5 . 我想实现侦听传入连接的TCP Socket Server,将一些数据发送到每个客户端,并在客户端断开连接时停止生成数据 .

这是示例代码

void main() {
  ServerSocket.bind(
      InternetAddress.ANY_IP_V4,
      9000).then((ServerSocket server) {
    runZoned(() {
      server.listen(handleClient);
    }, onError: (e) {
      print('Server error: $e');
    });
  });
}

void handleClient(Socket client) {
  client.done.then((_) {
    print('Stop sending');
  });
  print('Send data');
}

此代码接受连接并打印“发送数据” . 但即使客户离开,也永远不会打印“停止发送” .

问题是:如何在侦听器中捕获客户端断开连接?

1 回答

  • 4

    套接字是双向的,即它具有输入流和输出接收器 . 当通过调用Socket.close()关闭输出接收器时,将调用done返回的Future .

    如果您希望在输入流关闭时收到通知,请尝试使用Socket.drain() .

    请参阅下面的示例 . 您可以使用telnet进行测试 . 当您连接到服务器时,它将发送字符串“发送” . 每一秒 . 当您关闭telnet(ctrl-],然后键入关闭) . 服务器将打印“停止” .

    import 'dart:io';
    import 'dart:async';
    
    void handleClient(Socket socket) {
    
      // Send a string to the client every second.
      var timer = new Timer.periodic(
          new Duration(seconds: 1), 
          (_) => socket.writeln('Send.'));
    
      // Wait for the client to disconnect, stop the timer, and close the
      // output sink of the socket.
      socket.drain().then((_) {
        print('Stop.');    
        timer.cancel();
        socket.close();
      });
    }
    
    void main() {
      ServerSocket.bind(
          InternetAddress.ANY_IP_V4,
          9000).then((ServerSocket server) {
        runZoned(() {
          server.listen(handleClient);
        }, onError: (e) {
          print('Server error: $e');
        });
      });
    }
    

相关问题