Shelf router with isolates?
Closed this issue · 1 comments
sukhcha-in commented
How can we use Shelf ROuter with isolates?
import 'dart:io';
import 'dart:isolate';
void main() async {
for (var i = 1; i < 6; i++) {
Isolate.spawn(_startServer, []);
}
_startServer();
print('Serving at http://localhost:8080/');
await ProcessSignal.sigterm.watch().first;
}
void _startServer([List? args]) async {
final server = await HttpServer.bind(
InternetAddress.loopbackIPv4,
8080,
shared: true,
);
await for (final request in server) {
_handleRequest(request);
}
}
void _handleRequest(HttpRequest request) async {
request.response.write('Hello, world!');
await request.response.close();
}
sukhcha-in commented
Solved using shelf_io:
import 'dart:io';
import 'dart:isolate';
import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
class Routes {
Handler get handler {
final router = Router();
router.get('/', (Request request) async {
return Response.ok("Hello from isolate ${Isolate.current.hashCode}");
});
return router;
}
}
void main() async {
int numberOfCores = Platform.numberOfProcessors;
for (var i = 1; i < numberOfCores; i++) {
Isolate.spawn(_startServer, []);
}
_startServer([]);
await ProcessSignal.sigterm.watch().first;
}
void _startServer(List args) async {
final routes = Routes();
var server = await shelf_io.serve(
routes.handler,
InternetAddress.loopbackIPv4,
8080,
shared: true,
);
server.autoCompress = true;
print(
'Serving at http://${server.address.host}:${server.port} - isolate: ${Isolate.current.hashCode}');
}