ladybird/Userland/Services/EchoServer/Client.cpp
sin-ack dbd25916a3 LibCore+Userland+Tests: Convert Stream APIs to construct on heap
As per previous discussion, it was decided that the Stream classes
should be constructed on the heap.

While I don't personally agree with this change, it does have the
benefit of avoiding Function object reconstructions due to the lambda
passed to Notifier pointing to a stale object reference. This also has
the benefit of not having to "box" objects for virtual usage, as the
objects come pre-boxed.

However, it means that we now hit the heap everytime we construct a
TCPSocket for instance, which might not be desirable.
2022-01-13 15:16:12 +03:30

56 lines
1.3 KiB
C++

/*
* Copyright (c) 2020, the SerenityOS developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include "Client.h"
#include "LibCore/EventLoop.h"
Client::Client(int id, NonnullOwnPtr<Core::Stream::TCPSocket> socket)
: m_id(id)
, m_socket(move(socket))
{
m_socket->on_ready_to_read = [this] {
if (m_socket->is_eof())
return;
auto result = drain_socket();
if (result.is_error()) {
dbgln("Failed while trying to drain the socket: {}", result.error());
Core::deferred_invoke([this, strong_this = NonnullRefPtr(*this)] { quit(); });
}
};
}
ErrorOr<void> Client::drain_socket()
{
NonnullRefPtr<Client> protect(*this);
auto maybe_buffer = ByteBuffer::create_uninitialized(1024);
if (!maybe_buffer.has_value())
return ENOMEM;
auto buffer = maybe_buffer.release_value();
while (TRY(m_socket->can_read_without_blocking())) {
auto nread = TRY(m_socket->read(buffer));
dbgln("Read {} bytes.", nread);
if (m_socket->is_eof()) {
Core::deferred_invoke([this, strong_this = NonnullRefPtr(*this)] { quit(); });
break;
}
TRY(m_socket->write({ buffer.data(), nread }));
}
return {};
}
void Client::quit()
{
m_socket->close();
if (on_exit)
on_exit();
}