module d_webservice_example.controller.todo_notification_controller; import vibe.http.websockets : WebSocket; import vibe.web.web : path; @path("/api/v1/rt") class TodoNotificationController { import d_webservice_example.business.todo_notification_service : TodoNotificationService; private: TodoNotificationService todoNotificationService; public: this(TodoNotificationService todoNotificationService) nothrow pure @nogc @safe { this.todoNotificationService = todoNotificationService; } @path("/todos") void getWebsocket(scope WebSocket socket) @safe { import d_webservice_example.data.todo_notification : TodoNotification; import d_webservice_example.transport.todo_notification_cto : TodoNotificationCTO; import vibe.core.log : logDiagnostic; logDiagnostic("Received request for todo notifications via web socket connection"); auto callback = (scope const TodoNotification todoNotification) { import d_webservice_example.mapper.todo_notification_mapper : asTodoNotificationCTO; import vibe.data.json : serializeToJsonString; logDiagnostic("Sending todo notification to client"); socket.send(todoNotification.asTodoNotificationCTO.serializeToJsonString); }; todoNotificationService.registerListener(callback); dropWebsocketInput(socket); todoNotificationService.unRegisterListener(callback); logDiagnostic("Client disconnected from web socket connection: %s(%s)", socket.closeReason, socket.closeCode); } } private: void dropWebsocketInput(scope WebSocket socket) @safe { while (socket.connected) { socket.waitForData; if (socket.connected) socket.receive((scope IncomingWebSocketMessage) {}); } }