How to handle socket disconnects in Dart?

I'm using Dart 1.8.5 on server. I want to implement TCP Socket Server that listens to incoming connections, sends some data to every client and stops to generate data when client disconnects.

Here is the sample code

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');
}

This code accepts connections and prints "Send data". But it will never print "Stop sending" even if client was gone.

The question is: how to catch client disconnect in listener?


A Socket is bidirectional, ie it has an input stream and an output sink. The Future returned by done is called when the output sink is closed by calling Socket.close().

If you want to be notified when the input stream closes try using Socket.drain() instead.

See the example below. You can test it with telnet. When you connect to the server it will send the string "Send." every second. When you close telnet (ctrl-], and then type close). The server will print "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');
    });
  });
}
链接地址: http://www.djcxy.com/p/84020.html

上一篇: 闪亮的R按钮对齐

下一篇: 如何处理Dart中的套接字断开连接?