fluttertcpserver

Is there anything in TCP Server that is triggered when the client disconnects?


I am creating a TCP Server as follows. When the client connects, I add it to a list. It works smoothly. But I couldn't find out how to know if the client disconnects on its own accord. The "client.done.then" field is triggered if the server disconnects the connection intentionally. Is there such an event handler?

  Future<void> startServer(String ipAddress, int port) async {
server = await ServerSocket.bind(ipAddress, port);
server.listen((Socket client) {
  print(
      'Client connected: ${client.remoteAddress.address}:${client.remotePort}');
  addDevice(client);
  client.listen((data) {
    String dataString = utf8.decode(data);
    print(dataString);
  });

  client.done.then((value) {
    print(
        'Client disconnected: ${client.remoteAddress.address}:${client.remotePort}');
    removeDevice(client); // Bağlantı kesildiğinde cihazı listeden kaldır
  });
});

setState(() {
  isConnected = true;
});

}

Also, when I shut down the server, the client is not informed that the connected client has been shut down. When I want to close it as follows, I get an error.

  void stopServer() {
for (Socket client in connectedDevices) {
  client.close();
}
server.close();
setState(() {
  isConnected = false;
});

}

OS Error: Transport endpoint is not connected, errno = 107


Solution

  • The TCP connection you created is implemented in Dart as a stream, which emits events for incoming data. When a client disconnects, the stream closes, which triggers the done event. To define a callback for that event, you can pass a function as the onDone named parameter when calling the listen method of a stream. So you can rewrite your code as follows:

    client.listen((data) {
      String dataString = utf8.decode(data);
      print(dataString);
    }, onDone: () {
      print('Client disconnected: ${client.remoteAddress.address}:${client.remotePort}');
      removeDevice(client);
    });