A full non-blocking TCP server handling multiple clients in a signle tread.
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <utility>
class EchoServer
{
static constexpr std::size_t MaxPending = 256 * 1024;
struct Client
{
std::string output;
std::size_t sent = 0;
bool inputClosed = false;
std::size_t queued() const noexcept { return output.size() - sent; }
};
public:
explicit EchoServer(unsigned short port)
{
m_listener.bind("127.0.0.1", port);
m_listener.listen();
m_listener.setBlocking(false);
std::cout << "Listening on 127.0.0.1:" << m_listener.getLocalPort() << "\n";
}
void run() { m_events.run(); }
void stop() { m_events.stop(); }
private:
{
throw std::runtime_error("Listening socket failure");
while (auto incoming = m_listener.accept())
{
const int fd = incoming->nativeHandle();
auto client = std::make_unique<Client>(std::move(*incoming));
m_clients.emplace(fd, std::move(client));
std::cout << "Connected fd=" << fd << "\n";
}
}
void closeClient(int fd)
{
m_events.remove(fd);
m_clients.erase(fd);
std::cout << "Closed fd=" << fd << "\n";
}
void readClient(Client& client)
{
char buffer[8192];
while (!client.inputClosed && client.queued() < MaxPending)
{
const auto capacity = std::min(sizeof(buffer), MaxPending - client.queued());
const NET::IOResult result = client.socket.receive(buffer, capacity);
if (client.sent != 0) {
client.output.erase(0, client.sent);
client.sent = 0;
}
client.output.append(buffer, result.
bytes);
break;
client.inputClosed = true;
break;
} else {
throw std::runtime_error("Unexpected TCP receive status");
}
}
}
void writeClient(Client& client)
{
while (client.queued() != 0)
{
const auto position = client.output.data() + client.sent;
const NET::IOResult result = client.socket.send(position, client.queued());
if (result.
bytes == 0)
break;
client.sent += result.
bytes;
break;
throw std::runtime_error("Peer disconnected during send");
} else {
throw std::runtime_error("Unexpected TCP send status");
}
}
if (client.queued() == 0) {
client.output.clear();
client.sent = 0;
}
}
{
const auto it = m_clients.find(fd);
if (it == m_clients.end()) return;
Client& client = *it->second;
try {
if (!client.inputClosed &&
readClient(client);
if (client.queued() != 0)
writeClient(client);
closeClient(fd);
return;
}
closeClient(fd);
return;
}
if (client.inputClosed && client.queued() == 0) {
closeClient(fd);
return;
}
if (!client.inputClosed && client.queued() < MaxPending)
if (client.queued() != 0)
m_events.modify(fd, interests);
} catch (const std::exception& e) {
std::cerr << "Client " << fd << ": " << e.what() << "\n";
closeClient(fd);
}
}
std::unordered_map<int, std::unique_ptr<Client>> m_clients;
};
int main(int argc, char** argv)
{
try
{
const int port = (argc == 2) ? std::stoi(argv[1]) : 47777;
if (argc > 2 || port <= 0 || port > 65535)
throw std::invalid_argument("Usage: TCP_Event_Server [1..65535]");
EchoServer server(static_cast<unsigned short>(port));
server.run();
return 0;
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
return 1;
}
}
void setReuseAddress(bool enable)
Enable or disable local address reuse.