MultiServer.h 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Error.h>
  8. #include <AK/Function.h>
  9. #include <LibCore/LocalServer.h>
  10. #include <LibIPC/ConnectionFromClient.h>
  11. namespace IPC {
  12. template<typename ConnectionFromClientType>
  13. class MultiServer {
  14. public:
  15. static ErrorOr<NonnullOwnPtr<MultiServer>> try_create(Optional<ByteString> socket_path = {})
  16. {
  17. auto server = TRY(Core::LocalServer::try_create());
  18. TRY(server->take_over_from_system_server(socket_path.value_or({})));
  19. return adopt_nonnull_own_or_enomem(new (nothrow) MultiServer(move(server)));
  20. }
  21. Function<void(ConnectionFromClientType&)> on_new_client;
  22. private:
  23. explicit MultiServer(NonnullRefPtr<Core::LocalServer> server)
  24. : m_server(move(server))
  25. {
  26. m_server->on_accept = [&](auto client_socket) {
  27. auto client_id = ++m_next_client_id;
  28. auto client = IPC::new_client_connection<ConnectionFromClientType>(move(client_socket), client_id);
  29. if (on_new_client)
  30. on_new_client(*client);
  31. };
  32. }
  33. int m_next_client_id { 0 };
  34. RefPtr<Core::LocalServer> m_server;
  35. };
  36. }