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.
- server.dart
- client.dart
- Install
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();
}
import 'dart:io';
import 'package:crdt_lf/crdt_lf.dart';
import 'package:crdt_socket_sync/web_socket_client.dart';
/// Opens the note [documentId] and connects it to the server at [url].
///
/// [onStatus] gets every move of the connection status.
Future<({WebSocketClient client, CRDTFugueTextHandler text})> connectClient(
String url, {
String documentId = 'notes',
void Function(ConnectionStatus status)? onStatus,
}) async {
// The same documentId on every client: the server registered it.
final document = CRDTDocument(
documentId: documentId,
peerId: PeerId.generate(),
);
final text = CRDTFugueTextHandler(document, 'body');
final client = WebSocketClient(
url: url,
document: document,
author: document.peerId,
);
client.connectionStatus.listen(onStatus);
// Returns false when the handshake fails (DOCUMENT_NOT_FOUND, say),
// and the client retries on its own.
await client.connect();
return (client: client, text: text);
}
/// A short description of [status], for a log or a status bar.
String describe(ConnectionStatus status) {
return switch (status) {
ConnectionStatus.connecting => 'Connecting…',
ConnectionStatus.connected => 'Online',
ConnectionStatus.reconnecting => 'Connection lost, retrying…',
ConnectionStatus.disconnected => 'Offline',
ConnectionStatus.error => 'Connection error',
// Terminal: the server refused this build. Ask the user to update.
ConnectionStatus.unsupported => 'Update required',
};
}
Future<void> main(List<String> args) async {
final (:client, :text) = await connectClient(
'ws://localhost:8080',
onStatus: (status) => stdout.writeln(describe(status)),
);
client.document.updates.listen((_) => stdout.writeln(text.value));
// A local edit: the client sends it to the server on its own.
text.insert(
text.value.runes.length,
'${args.isEmpty ? 'Hello' : args.join(' ')}\n',
);
await ProcessSignal.sigint.watch().first;
await client.disconnect();
client.dispose();
client.document.dispose();
}
dart pub add crdt_lf crdt_socket_sync
Key points
- Register the document on the server with
addDocument: a client of an unknown document getsDOCUMENT_NOT_FOUNDand theerrorstatus. - 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.
InMemoryCRDTServerRegistryloses the note on restart. For durable documents, usePersistentServerRegistry.