bind static method

Future<WsServerEndpoint> bind({
  1. required Object host,
  2. required int port,
  3. required SecurityContext securityContext,
  4. required OnConnection onConnection,
  5. FrameCodec codecFactory()?,
})

Binds and starts a TLS WebSocket endpoint on host:port.

securityContext must provide the server certificate chain and private key. onConnection receives every accepted connection. Pass port: 0 to bind an ephemeral port (useful in tests); read port afterwards.

Implementation

static Future<WsServerEndpoint> bind({
  required Object host,
  required int port,
  required SecurityContext securityContext,
  required OnConnection onConnection,
  FrameCodec Function()? codecFactory,
}) async {
  final handler = webSocketHandler((channel, _) {
    onConnection(
      WebSocketConnection.fromChannel(
        channel,
        codec: codecFactory?.call() ?? FrameCodec.standard(),
      ),
    );
  });

  final server = await shelf_io.serve(
    const Pipeline().addHandler(handler),
    host,
    port,
    securityContext: securityContext,
  );
  return WsServerEndpoint._(server);
}