https://pub.dartlang.org/packages/shelf_web_socket显示了这个例子
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_web_socket/shelf_web_socket.dart';
void main() {
var handler = webSocketHandler((webSocket) {
webSocket.listen((message) {
webSocket.add("echo $message");
});
});
shelf_io.serve(handler, 'localhost', 8080).then((server) {
print('Serving at ws://${server.address.host}:${server.port}');
});
}
我想知道如何将它与我的 HTTP 服务器初始化结合起来
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as sIo;
import 'package:shelf_auth/shelf_auth.dart' as sAuth;
import 'package:shelf_auth/src/authentication.dart' as sAuth2;
import 'package:option/option.dart';
import 'package:shelf_web_socket/shelf_web_socket.dart' as sWs;
...
var authMiddleware = sAuth.authenticate(
[new MyAuthenticator()],
sessionHandler: new sAuth.JwtSessionHandler('bla', 'blub', new UserLookup()),
allowHttp: true,
allowAnonymousAccess: false);
var handler = const shelf.Pipeline()
.addMiddleware(shelf.logRequests())
.addMiddleware(authMiddleware)
.addHandler(_handleHttpRequest);
// var wsHandler = sWs.webSocketHandler(_handleWebSocketConnect);
sIo.serve(handler, '0.0.0.0', servePort).then((server) {
_log.finest('Serving at http://${server.address.host}:${server.port}');
});
需要做什么才能wsHandler
调用 WebSocket 连接并handler
继续处理 HTTP 请求(如果可能在同一个端口上),如果可能的话,使用配置的身份验证和会话管理。
我在不同的端口上尝试了它,但使用了身份验证/会话中间件(不知道这是否应该一起使用)
var authMiddleware = sAuth.authenticate(
[new MyAuthenticator()],
sessionHandler: new sAuth.JwtSessionHandler('bla', 'blub', new UserLookup()),
allowHttp: true,
allowAnonymousAccess: false);
var handler = const shelf.Pipeline()
.addMiddleware(shelf.logRequests())
.addMiddleware(authMiddleware)
.addHandler(_handleHttpRequest);
sIo.serve(handler, '0.0.0.0', servePort).then((server) {
_log.finest('Serving at http://${server.address.host}:${server.port}');
});
var wsHandler = const shelf.Pipeline()
.addMiddleware(shelf.logRequests())
.addMiddleware(authMiddleware)
.addHandler(sWs.webSocketHandler(_handleWebSocketConnect));
sIo.serve(wsHandler, '0.0.0.0', servePort + 1).then((server) {
_log.finest('Serving at ws://${server.address.host}:${server.port}');
});
并得到
Illegal argument(s): webSocketHandler may only be used with a server that supports request hijacking.