start method
Starts the server.
If port
is not provided, it will use 8080.
If port
is 0
, it will use a random port chosen by the OS.
If address
is not provided, it will use localhost
, 127.0.0.1
, 0.0.0.0
or ::1
If the server fails to start, it will print an error message and exit with code 1.
If the server starts successfully, it will print a success message, and the server will listen for incoming requests.
If the server is interrupted with Ctrl+C, it will shutdown the server, delete the rate limit file if it exists, and exit with code 0.
Implementation
Future<void> start({String address = '0.0.0.0', int port = 8080}) async {
try {
_server = await HttpServer.bind(address, port);
} on SocketException catch (e) {
if (e.osError!.errorCode == 10048) {
print(
'[dartcore] Port is already in use, try to use to a different port.');
exit(1);
} else {
print(
'[dartcore] Failed to start server: OS ERROR ${e.osError!.errorCode}, ${e.osError!.message}');
exit(1);
}
} catch (e) {
print('[dartcore] Failed to start server:');
print(e);
exit(1);
}
print(
'[dartcore] Server running on ${_server!.address.address}:${_server!.port}\n[dartcore] Press Ctrl+C to shutdown the Server.');
emit('serverStarted', {'address': address, 'port': port});
ProcessSignal.sigint.watch().listen((_) async {
final file = File(_rateLimiter!.storagePath);
if (await file.exists()) {
await file.delete();
}
await shutdown();
exit(0);
});
await for (HttpRequest request in _server!) {
await _handleRequest(request, Response(request: request));
}
}