'Dart shelf_web_socket with shelf_router gives Hijack exception

I am trying to implement a basic server which serves both websockets and http requests.

Code is this;

import 'package:shelf_router/shelf_router.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_web_socket/shelf_web_socket.dart';

void main(List<String> args) async {
  var app = Router();

  var wsHandle = webSocketHandler((webSocket) {
    webSocket.stream.listen((message) {
      print(message);
      webSocket.sink.add("echo $message");
    });
  });

  app.get('/', (Request r) {
    return Response.ok('hello-world');
  });

  app.get("/ws", wsHandle);

  var server = await io.serve(app, 'localhost', 8080);
  print("Server is on at ${server.address.host} ${server.port}");
}

When I try to connect the ws url I get Hijack Error.

Exception has occurred.
HijackException (A shelf request's underlying data stream was hijacked.
This exception is used for control flow and should only be handled by a Shelf adapter.)

I could not find a workaround. This solution does not work for me.



Solution 1:[1]

Your code works just switch app.get("/ws") and app.get("/").

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Steven