platform/packages/websocket/example/main.dart

60 lines
1.7 KiB
Dart
Raw Normal View History

2018-12-09 16:40:09 +00:00
import 'dart:io';
2021-05-15 07:19:35 +00:00
import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_framework/http.dart';
import 'package:angel3_framework/http2.dart';
import 'package:angel3_websocket/server.dart';
2018-12-09 16:40:09 +00:00
import 'package:file/local.dart';
import 'package:logging/logging.dart';
2018-07-10 16:54:55 +00:00
2021-04-10 15:12:43 +00:00
void main(List<String> args) async {
var app = Protevus();
var http = ProtevusHttp(app);
var ws = ProtevusWebSocket(app, sendErrors: !app.environment.isProduction);
2018-12-09 16:40:09 +00:00
var fs = const LocalFileSystem();
2022-10-06 00:00:03 +00:00
app.logger = Logger('angel3_websocket');
2018-07-10 16:54:55 +00:00
// This is a plug-in. It hooks all your services,
// to automatically broadcast events.
await app.configure(ws.configureServer);
2018-12-09 16:40:09 +00:00
app.get('/', (req, res) => res.streamFile(fs.file('example/index.html')));
2018-07-10 16:54:55 +00:00
// Listen for requests at `/ws`.
2018-12-09 16:40:09 +00:00
app.get('/ws', ws.handleRequest);
app.fallback((req, res) => throw ProtevusHttpException.notFound());
2018-12-09 16:40:09 +00:00
ws.onConnection.listen((socket) {
2022-10-06 00:00:03 +00:00
var h = socket.request.headers;
print('WebSocket onConnection $h');
2018-12-09 16:40:09 +00:00
socket.onData.listen((x) {
socket.send('pong', x);
});
});
if (args.contains('http2')) {
2021-04-10 15:12:43 +00:00
var ctx = SecurityContext()
2018-12-09 16:40:09 +00:00
..useCertificateChain('dev.pem')
..usePrivateKey('dev.key', password: 'dartdart');
try {
ctx.setAlpnProtocols(['h2'], true);
} catch (e, st) {
2022-02-22 00:07:01 +00:00
app.logger.severe(
2018-12-09 16:40:09 +00:00
'Cannot set ALPN protocol on server to `h2`. The server will only serve HTTP/1.x.',
e,
st,
);
}
2018-07-10 16:54:55 +00:00
var http2 = ProtevusHttp2(app, ctx);
2019-05-01 22:58:47 +00:00
http2.onHttp1.listen(http.handleRequest);
2018-12-09 16:40:09 +00:00
await http2.startServer('127.0.0.1', 3000);
print('Listening at ${http2.uri}');
} else {
await http.startServer('127.0.0.1', 3000);
print('Listening at ${http.uri}');
}
2018-07-10 16:54:55 +00:00
}