listen function

Future<void> listen(
  1. Crdt crdt,
  2. int port, {
  3. Duration? pingInterval = defaultPingInterval,
  4. ServerHandshakeDataBuilder? handshakeDataBuilder,
  5. ChangesetBuilder? changesetBuilder,
  6. RecordValidator? validateRecord,
  7. ChangesetMapper? mapIncomingChangeset,
  8. void onConnecting(
    1. HttpRequest request
    )?,
  9. ServerOnConnect? onConnect,
  10. OnDisconnect? onDisconnect,
  11. OnChangeset? onChangesetReceived,
  12. OnChangeset? onChangesetSent,
  13. void onUpgradeError(
    1. Object error,
    2. HttpRequest request
    )?,
  14. bool verbose = false,
})

Opens an HTTP socket and starts listening for incoming connections on the specified port.

pingInterval defines the WebSocket heartbeat frequency and allows the server to identify and release stale connections. This is highly recommended since stale connections keep database subscriptions which cause queries to be run on every change. Defaults to 20 seconds, set to null to disable.

Use onConnection to monitor incoming HTTP connections.

onUpgradeError can be used to monitor connection->websocket upgrade errors.

See CrdtSync.server for a description of the remaining parameters.

Implementation

Future<void> listen(
  Crdt crdt,
  int port, {
  Duration? pingInterval = defaultPingInterval,
  ServerHandshakeDataBuilder? handshakeDataBuilder,
  ChangesetBuilder? changesetBuilder,
  RecordValidator? validateRecord,
  ChangesetMapper? mapIncomingChangeset,
  void Function(HttpRequest request)? onConnecting,
  ServerOnConnect? onConnect,
  OnDisconnect? onDisconnect,
  OnChangeset? onChangesetReceived,
  OnChangeset? onChangesetSent,
  void Function(Object error, HttpRequest request)? onUpgradeError,
  bool verbose = false,
}) async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, port);
  if (verbose) print('Listening on localhost:${server.port}');

  await for (HttpRequest request in server) {
    onConnecting?.call(request);
    try {
      await upgrade(
        crdt,
        request,
        pingInterval: pingInterval,
        handshakeDataBuilder: handshakeDataBuilder,
        changesetBuilder: changesetBuilder,
        validateRecord: validateRecord,
        mapIncomingChangeset: mapIncomingChangeset,
        onConnect: onConnect,
        onDisconnect: onDisconnect,
        onChangesetReceived: onChangesetReceived,
        onChangesetSent: onChangesetSent,
        verbose: verbose,
      );
    } catch (e) {
      if (verbose) print(e);
      onUpgradeError?.call(e, request);
    }
  }
}