ClientServerProject/project/client.h

32 lines
995 B
C++

#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));
if (!remote_address || net::connect(socket, remote_address) < 0)
return std::thread();
auto thread = std::thread(&client::accept_message, this);
return thread;
}
};