Graceful shutdown

The server now correctly shuts down within at most 2000 ms and
rudimentary error handling is introduced in the core loop.