readFromClients method

Future<void> readFromClients()

Implementation

Future<void> readFromClients() async {
  _online =
      true; // assume online unless server doesnt respond after 5 seconds

  Timer.periodic(const Duration(seconds: 5), (_) {
    if (!_closed) {
      _clientMap.cleanUp();
    }
  });

  _listenSocket.asStream().listen((packet) async {
    // receive packets from clients
    if (packet != null) {
      var endpoint = Endpoint.unicast(packet.address,
          port: Port(packet.port)); // client endpoint

      if (packet.data[0] == Constants.unconnectedPingId && !_online) {
        _listenSocket.send(
            _rewritePong(UnconnectedPing.offlinePong.toBytes()), endpoint);
      }

      // send packet to server after intercept
      _clientMap.get(endpoint, readFromServer).then(
          (sendSocket) => sendSocket.send(packet.data, _serverEndpoint));
    }
  });
}