2021-02-11 02:26:38 -05:00
|
|
|
#pragma once
|
|
|
|
#include "../libraries/event.h"
|
|
|
|
#include "networked.h"
|
|
|
|
#include <thread>
|
|
|
|
|
|
|
|
class client : public networked
|
|
|
|
{
|
|
|
|
auto accept_message() -> void //add const later
|
|
|
|
{
|
|
|
|
while(is_valid()) /* Accept all messages */
|
|
|
|
{
|
|
|
|
auto message = receive_message();
|
|
|
|
if (message.empty() && is_valid()) //connection is closed or broken.
|
|
|
|
{
|
|
|
|
disconnect();
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
message_received.execute(message);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
public:
|
|
|
|
event<std::string&> message_received {};
|
|
|
|
explicit client() : networked(net::socket(AF_INET, SOCK_STREAM, 0)){}
|
|
|
|
auto connect(const std::string& ip, const port port) -> std::thread
|
|
|
|
{
|
|
|
|
auto remote_address = net::getaddrinfo(ip, std::to_string(port));
|
2021-02-12 03:19:18 -05:00
|
|
|
if (!remote_address || net::connect(socket, remote_address) < 0)
|
2021-02-11 02:26:38 -05:00
|
|
|
return std::thread();
|
|
|
|
auto thread = std::thread(&client::accept_message, this);
|
|
|
|
return thread;
|
|
|
|
}
|
|
|
|
};
|