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

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

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

HttpRequest ClientConnection::read_request()
{
	// TODO: Clean up this code to ensure it works with multiple lines
	//       and not risk a buffer overflow.
	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);
	}

	return HttpRequest(buffer);
}

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

	std::string result = response.to_string();
	write(m_socket_fd, result.c_str(), result.length());

	return true;
}

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