我正在尝试实现一个同时服务于 websockets 和 http 请求的基本服务器。
代码是这样的;
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}");
}
当我尝试连接 ws url 时,我得到了劫持错误。
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.)
我找不到解决方法。这个解决方案对我不起作用。