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.
Your code works just switch app.get("/ws") and app.get("/").