Skip to main content

A real-time note: a Dart server and its clients

A server in server–client mode holds the documents it knows, merges every change, and sends it to the other clients. Run the server, then two clients: what one types, the other prints.

A real-time note: a Dart server and its clientsSource ↗

A Dart server that holds one shared note, and a client that edits it. Every client that opens the same document sees the edits of the others live.

Dart VMFlutter nativeâś“ tested in CI
import 'dart:io';

import 'package:crdt_socket_sync/web_socket_server.dart';

/// Starts a sync server on [port] that hosts the note `notes`.
Future<WebSocketServer> startServer({int port = 8080}) async {
final registry = InMemoryCRDTServerRegistry();

// The server answers DOCUMENT_NOT_FOUND for a document it does not hold.
await registry.addDocument('notes');

final server = WebSocketServer(
serverFactory: () => HttpServer.bind(InternetAddress.anyIPv4, port),
serverRegistry: registry,
);
await server.start();
return server;
}

Future<void> main() async {
final server = await startServer();
stdout.writeln('Serving "notes" on ws://localhost:${server.port}');

// Ctrl+C closes every client session, then the HTTP server.
await ProcessSignal.sigint.watch().first;
await server.dispose();
}

Key points

  • Register the document on the server with addDocument: a client of an unknown document gets DOCUMENT_NOT_FOUND and the error status.
  • Every client opens the document with the same documentId.
  • Local edits sync on their own: the client sends each change, and the server rebroadcasts it to the others.
  • InMemoryCRDTServerRegistry loses the note on restart. For durable documents, use PersistentServerRegistry.