How to handle connector disconnect in Dart?

I am using Dart 1.8.5 on the server. I want to implement a TCP Socket Server that listens for incoming connections, sends some data to each client, and stops to generate data when the client disconnects.

Here is a 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 the connection and displays "Send data." But he will never print β€œStop sending,” even if the customer has left.

The question arises: how to catch a client break in the listener?

+7
dart sockets
source share
1 answer

Socket is bidirectional, that is, it has an input stream and an output receiver. 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 is closed, try Socket.drain () instead.

See the example below. You can test it with telnet. When you connect to the server, it will send the string "Submit". every second. When you close telnet (ctrl-], 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'); }); }); } 
+4
source share

All Articles