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

lig*_*lig 7 sockets dart

我在服务器上使用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');
}
Run Code Online (Sandbox Code Playgroud)

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

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

Gre*_*owe 4

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

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

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

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');
    });
  });
}
Run Code Online (Sandbox Code Playgroud)