websocket static method

Route websocket(
  1. String route,
  2. WebSocketHandler handler, {
  3. List middleware = const <dynamic>[],
  4. List<String>? allowedOrigins,
  5. int maxMessageSize = 16 * 1024 * 1024,
})

raw WebSocket route. handler gets the open socket. Middleware runs first, so it can check auth. For rooms, acks and the socket.io clients, use dox_socketio.

By default any site can open the socket from a browser, with the cookies of the user. To check the Origin, set allowedOrigins (or AppConfig.webSocketAllowedOrigins for every route). Then only pages of the same host and the listed sites, like https://app.example.com, can open it. [] means the same host only. * allows every site. Other origins get 403. A client with no Origin header (not a browser) is always allowed.

A message or frame over maxMessageSize bytes (default 16 MB) closes the socket with 1009 before your code gets it.

Route.websocket('echo', (WebSocket socket, DoxRequest req) {
  socket.listen(socket.add);
});

Implementation

static Route websocket(
  String route,
  WebSocketHandler handler, {
  List<dynamic> middleware = const <dynamic>[],
  List<String>? allowedOrigins,
  int maxMessageSize = 16 * 1024 * 1024,
}) {
  if (maxMessageSize < 1) {
    throw ArgumentError.value(
      maxMessageSize,
      'maxMessageSize',
      'must be 1 or more',
    );
  }
  Route r = Route()._addRoute(
    HttpRequestMethod.GET,
    Route()._join(route),
    <dynamic>[
      ...middleware,
      _WebSocketRoute(handler, allowedOrigins, maxMessageSize).call,
    ],
  );
  if (allowedOrigins == null) _noOriginCheck[r._last!] = true;
  return r;
}