Client.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Client.h"
  7. #include <LibCore/EventLoop.h>
  8. Client::Client(int id, NonnullOwnPtr<Core::Stream::TCPSocket> socket)
  9. : m_id(id)
  10. , m_socket(move(socket))
  11. {
  12. m_socket->on_ready_to_read = [this] {
  13. if (m_socket->is_eof())
  14. return;
  15. auto result = drain_socket();
  16. if (result.is_error()) {
  17. dbgln("Failed while trying to drain the socket: {}", result.error());
  18. Core::deferred_invoke([this, strong_this = NonnullRefPtr(*this)] { quit(); });
  19. }
  20. };
  21. }
  22. ErrorOr<void> Client::drain_socket()
  23. {
  24. NonnullRefPtr<Client> protect(*this);
  25. auto buffer = TRY(ByteBuffer::create_uninitialized(1024));
  26. while (TRY(m_socket->can_read_without_blocking())) {
  27. auto bytes_read = TRY(m_socket->read(buffer));
  28. dbgln("Read {} bytes.", bytes_read.size());
  29. if (m_socket->is_eof()) {
  30. Core::deferred_invoke([this, strong_this = NonnullRefPtr(*this)] { quit(); });
  31. break;
  32. }
  33. TRY(m_socket->write(bytes_read));
  34. }
  35. return {};
  36. }
  37. void Client::quit()
  38. {
  39. m_socket->close();
  40. if (on_exit)
  41. on_exit();
  42. }