summaryrefslogtreecommitdiff
path: root/Userland/Services/EchoServer/Client.cpp
blob: d2150cd1c6a4851e9d3f71c6340e0692404016ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
 * Copyright (c) 2020, the SerenityOS developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include "Client.h"

Client::Client(int id, RefPtr<Core::TCPSocket> socket)
    : m_id(id)
    , m_socket(move(socket))
{
    m_socket->on_ready_to_read = [this] { drain_socket(); };
}

void Client::drain_socket()
{
    NonnullRefPtr<Client> protect(*this);
    while (m_socket->can_read()) {
        auto buf = m_socket->read(1024);

        dbgln("Read {} bytes.", buf.size());

        if (m_socket->eof()) {
            quit();
            break;
        }

        m_socket->write(buf);
    }
}

void Client::quit()
{
    m_socket->close();
    if (on_exit)
        on_exit();
}