ClientServerProject/project/server.h

59 lines
1.8 KiB
C
Raw Normal View History

2021-02-11 02:26:38 -05:00
#pragma once
#include "../libraries/event.h"
#include "../libraries/osyncstream.h"
#include "networked.h"
#include <thread>
class server : networked
{
auto accept_clients() -> void
{
while(is_valid())
{
auto client = networked(accept(socket, nullptr, nullptr));
client_connected.execute(client);
#ifdef THREADED
std::thread(&server::accept_client_message, this, client).detach();
#else
std::thread(&server::accept_client_message, this, client).join();
#endif
}
}
auto accept_client_message(networked client) -> void //add const later
{
while(client.is_valid()) /* Accept all messages */
{
auto message = client.receive_message();
if (message.empty() && client.is_valid()) //Client could have disconnected after check but PRIOR to recv.
{
sscout << "Client Connection Lost\n";
client.disconnect();
break;
}
message_received.execute(client, message);
}
}
public:
event<networked&> client_connected {};
event<networked&, std::string&> message_received {};
auto listen(const std::string& ip, const port port) -> std::thread
{
const auto address = net::getaddrinfo(ip, std::to_string(port));
if (net::bind(socket, address) < 0)
{
sscout << "Error binding.\n";
return std::thread();
}
if (net::listen(socket) < 0)
{
sscout << "Error listening.\n";
return std::thread();
}
sscout << "Listening ... \n";
return std::thread(&server::accept_clients, this);
}
explicit server() : networked(net::socket(AF_INET, SOCK_STREAM, 0)){}
};