Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle socket disconnects in Dart?

Tags:

sockets

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?

like image 971
lig Avatar asked Feb 26 '15 14:02

lig


1 Answers

A Socket is bidirectional, i.e. 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');
    });
  });
}
like image 165
Greg Lowe Avatar answered Sep 18 '22 22:09

Greg Lowe