ConnectionToServer.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <LibCore/Stream.h>
  8. #include <LibIPC/Connection.h>
  9. namespace IPC {
  10. #define IPC_CLIENT_CONNECTION(klass, socket_path) \
  11. C_OBJECT_ABSTRACT(klass) \
  12. public: \
  13. template<typename Klass = klass, class... Args> \
  14. static ErrorOr<NonnullRefPtr<klass>> try_create(Args&&... args) \
  15. { \
  16. auto socket = TRY(Core::Stream::LocalSocket::connect(socket_path)); \
  17. /* We want to rate-limit our clients */ \
  18. TRY(socket->set_blocking(true)); \
  19. \
  20. return adopt_nonnull_ref_or_enomem(new (nothrow) Klass(move(socket), forward<Args>(args)...)); \
  21. }
  22. template<typename ClientEndpoint, typename ServerEndpoint>
  23. class ConnectionToServer : public IPC::Connection<ClientEndpoint, ServerEndpoint>
  24. , public ClientEndpoint::Stub
  25. , public ServerEndpoint::template Proxy<ClientEndpoint> {
  26. public:
  27. using ClientStub = typename ClientEndpoint::Stub;
  28. using IPCProxy = typename ServerEndpoint::template Proxy<ClientEndpoint>;
  29. ConnectionToServer(ClientStub& local_endpoint, NonnullOwnPtr<Core::Stream::LocalSocket> socket)
  30. : Connection<ClientEndpoint, ServerEndpoint>(local_endpoint, move(socket))
  31. , ServerEndpoint::template Proxy<ClientEndpoint>(*this, {})
  32. {
  33. }
  34. virtual void die() override
  35. {
  36. // Override this function if you don't want your app to exit if it loses the connection.
  37. exit(0);
  38. }
  39. };
  40. }