summaryrefslogtreecommitdiff
path: root/src/ClientConnection.cpp
blob: 3bf93c3d533136b8363b7a1c22608208797013a3 (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
#include "ClientConnection.h"

#include <unistd.h>
#include <iostream>
#include <sstream>

ClientConnection::ClientConnection(int socket)
	: m_socket_fd(socket)
{
}

void ClientConnection::dump_request_data()
{
	constexpr int BUFFER_SIZE = 4096;
	char buffer[BUFFER_SIZE+1];
	int n;

	memset(buffer, 0, BUFFER_SIZE);
	while ((n = read(m_socket_fd, buffer, BUFFER_SIZE-1)) > 0) {
		std::cout << buffer;

		if (buffer[n-1] == '\n')
			break;

		memset(buffer, 0, BUFFER_SIZE);
	}
}

bool ClientConnection::send(const HttpResponse& response, const char* message)
{
	if (!m_is_open)
		return false;

	std::stringstream ss;
	ss << response.to_string()
	   << "\r\n\r\n"
	   << message;

	std::string result = ss.str();
	write(m_socket_fd, result.c_str(), result.length());

	return true;
}

void ClientConnection::close()
{
	m_is_open = false;
	::close(m_socket_fd);
}