summaryrefslogtreecommitdiff
path: root/src/session.cpp
blob: bfadb5dc2c48e40843e6fe5903a2d5a76165cb5c (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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include "session.hpp"
#include <cerrno>
#include <cstring>
#include <print>
#include <sys/socket.h>

CSession::CSession(Hyprutils::OS::CFileDescriptor sockfd)
	: m_sockfd(std::move(sockfd)) {
	if (!m_sockfd.isValid())
		throw std::runtime_error("Failed to create socket");
}

CSession::~CSession() {
	m_sockfd.reset();
}

void CSession::onConnect() const {
	std::println("Client connected");
}

void CSession::onDisconnect() const {
	std::println("Client disconnected");
}

void CSession::onErrno(eEventType eventType) const {
	const auto err = strerror(errno);
	switch (eventType) {
	case READ:
		std::println("Error while reading: {}", err);
	case WRITE:
		std::println("Error while writing: {}", err);
	}
}

void CSession::onRecv(SRecvData &data) const {
	std::println("Received: {}", data.data, data.dataSize);
}

void CSession::recvManager() {
	while (true) {
		CSession::SRecvData recvData = read();
		if (!recvData.good)
			break;
	}
}

CSession::SRecvData CSession::read() {
	SRecvData recvData;
	ssize_t	  dataSize = recv(m_sockfd.get(), recvData.data, recvData.dataSize, 0);
	if (dataSize < 0) {
		recvData.good = false;
		onErrno(READ);
	}
	if (dataSize == 0) {
		recvData.good = false;
		onDisconnect();
	}
	onRecv(recvData);
	return recvData;
}

CSession::SRecvData CSession::read(std::string &msg) {
	write(msg);
	return read();
}

void CSession::run() {
	onConnect();
	// std::jthread recvThread(&CSession::recvManager, this);
	registerSession();
	recvManager();
}

bool CSession::registerSession() {
	SRecvData recvData = read((std::string &)"Name: ");
	if (!recvData.good)
		return false;
	m_name = recvData.data;

	std::println("Client registered as: {}", m_name);

	return true;
}

bool CSession::isValid() const {
	return m_sockfd.isValid() && !m_name.empty();
}

bool CSession::write(const std::string &msg) const {
	bool	bad		 = false;
	ssize_t sentSize = send(m_sockfd.get(), msg.c_str(), msg.size(), 0);
	if (sentSize < 0) {
		bad = true;
		onErrno(WRITE);
	}
	return bad;
}

std::string CSession::getName() const {
	return m_name;
}