long_polling_channel 0.0.1 copy "long_polling_channel: ^0.0.1" to clipboard
long_polling_channel: ^0.0.1 copied to clipboard

StreamChannel wrappers for long polling.

example/long_polling_channel_example.dart

import 'dart:async';
import 'dart:io';

import 'package:long_polling_channel/long_polling_channel.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;

/// Demonstrates hosting a long polling endpoint with Shelf and interacting via
/// the client channel in the same process.
Future<void> main() async {
  // Set up a simple Shelf server that exposes a long polling endpoint.
  final handler = LongPollingHandler(
    Uri.parse('/long-poll'),
    pollTimeout: const Duration(seconds: 5),
  );

  final server = await shelf_io.serve(
    handler.handler,
    InternetAddress.loopbackIPv4,
    0,
  );

  print(
    'Long polling server running on '
    'http://localhost:${server.port}/long-poll',
  );

  // Connect a client channel to the server.
  final channel = LongPollingChannel.connect(
    Uri.parse('http://localhost:${server.port}/long-poll'),
  );

  // Wait for the server-side connection to be created and echo messages.
  final connections = handler.connections;
  unawaited(() async {
    final connection = await connections.next;

    connection.stream.listen((message) {
      print('Server received: $message');
      connection.sink.add('Echo: $message');
    });

    connection.sink.add('Hello from server');
  }());

  // Listen for messages from the server.
  final subscription = channel.stream.listen(
    (message) => print('Client received: $message'),
  );

  channel.sink.add('Hello from client');

  // Give the messages a chance to flow before shutting down.
  await Future<void>.delayed(const Duration(seconds: 2));

  await subscription.cancel();
  await channel.sink.close();
  await handler.shutdown();
  await connections.cancel();
  await server.close(force: true);

  print('Example complete.');
}
0
likes
150
points
114
downloads

Publisher

verified publisherjamiewest.dev

Weekly Downloads

StreamChannel wrappers for long polling.

Repository
View/report issues

Topics

#server #shelf

Documentation

API reference

License

MIT (license)

Dependencies

async, collection, http, pool, shelf, sse, stream_channel, uuid

More

Packages that depend on long_polling_channel