CLocalServer.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include <LibCore/CLocalServer.h>
  2. #include <LibCore/CLocalSocket.h>
  3. #include <LibCore/CNotifier.h>
  4. #include <stdio.h>
  5. #include <sys/socket.h>
  6. CLocalServer::CLocalServer(CObject* parent)
  7. : CObject(parent)
  8. {
  9. m_fd = socket(AF_LOCAL, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
  10. ASSERT(m_fd >= 0);
  11. }
  12. CLocalServer::~CLocalServer()
  13. {
  14. }
  15. bool CLocalServer::listen(const String& address)
  16. {
  17. if (m_listening)
  18. return false;
  19. int rc;
  20. auto socket_address = CSocketAddress::local(address);
  21. auto un = socket_address.to_sockaddr_un();
  22. rc = ::bind(m_fd, (const sockaddr*)&un, sizeof(un));
  23. ASSERT(rc == 0);
  24. rc = ::listen(m_fd, 5);
  25. ASSERT(rc == 0);
  26. m_listening = true;
  27. m_notifier = CNotifier::construct(m_fd, CNotifier::Event::Read, this);
  28. m_notifier->on_ready_to_read = [this] {
  29. if (on_ready_to_accept)
  30. on_ready_to_accept();
  31. };
  32. return true;
  33. }
  34. ObjectPtr<CLocalSocket> CLocalServer::accept()
  35. {
  36. ASSERT(m_listening);
  37. sockaddr_un un;
  38. socklen_t un_size = sizeof(un);
  39. int accepted_fd = ::accept(m_fd, (sockaddr*)&un, &un_size);
  40. if (accepted_fd < 0) {
  41. perror("accept");
  42. return nullptr;
  43. }
  44. return CLocalSocket::construct(accepted_fd);
  45. }