bindRpcWebSocketHttpServer function

Future<HttpServer> bindRpcWebSocketHttpServer(
  1. Object address,
  2. int port, {
  3. RpcSecurityPolicy policy = const RpcSecurityPolicy(),
  4. int? maxHeaderBytes,
  5. Duration? headerTimeout = const Duration(seconds: 60),
  6. int? maxConnections,
  7. int backlog = 0,
  8. bool v6Only = false,
  9. bool shared = false,
})

Binds an HttpServer for rpcWebSocketConnections that bounds what a connection may send before its upgrade request ends.

dart:io holds an unfinished request header block below every rpc_dart limit, for as long as the client keeps the connection open. A server bound here closes a connection whose header block passes maxHeaderBytes (by default four times what policy admits as one request's head) or takes longer than headerTimeout from the accept, and refuses connections past maxConnections (off by default: while attackers fill it, honest clients are refused too). The same bounds RpcHttpServer puts on its own socket.

Only the first header block is bounded: a connection here carries one upgrade request, and rpcWebSocketConnections closes any connection it refuses, so after the block ends the bytes are WebSocket frames, bounded by the frame guard.

Close the returned server as any other: closing it releases the port.

final http = await bindRpcWebSocketHttpServer(InternetAddress.anyIPv4, 8080);
final server = RpcWebSocketServer(
  connections: rpcWebSocketConnections(http),
  mode: RpcResponderMode.contracts([...]),
);

Implementation

Future<HttpServer> bindRpcWebSocketHttpServer(
  Object address,
  int port, {
  RpcSecurityPolicy policy = const RpcSecurityPolicy(),
  int? maxHeaderBytes,
  Duration? headerTimeout = const Duration(seconds: 60),
  int? maxConnections,
  int backlog = 0,
  bool v6Only = false,
  bool shared = false,
}) async {
  final socket = await ServerSocket.bind(
    address,
    port,
    backlog: backlog,
    v6Only: v6Only,
    shared: shared,
  );
  final bounded = RpcHeaderBoundedServerSocket(
    socket,
    maxHeaderBytes:
        maxHeaderBytes ??
        RpcHeaderBoundedServerSocket.defaultMaxHeaderBytes(policy),
    headerTimeout: headerTimeout,
    maxConnections: maxConnections,
  );
  return _BoundedHttpServer(HttpServer.listenOn(bounded), bounded);
}