-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_tcpServer.cpp
More file actions
158 lines (130 loc) · 4.31 KB
/
Copy pathhttp_tcpServer.cpp
File metadata and controls
158 lines (130 loc) · 4.31 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#include "http_tcpServer.h"
#include <cerrno>
#include <cstring>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <thread>
#include <utility>
#include <unistd.h>
namespace
{
constexpr int BUFFER_SIZE = 4096;
constexpr int CONNECTION_BACKLOG = 20;
void log(const std::string &message)
{
std::cout << message << std::endl;
}
std::runtime_error socketError(const std::string &message)
{
return std::runtime_error(message + ": " + std::strerror(errno));
}
}
namespace http
{
TcpServer::TcpServer(std::string ip_address, int port)
: m_ip_address(std::move(ip_address)),
m_port(port),
m_socket(-1),
m_sockAddress(),
m_sockAddress_len(sizeof(m_sockAddress))
{
startServer();
}
TcpServer::~TcpServer()
{
closeServer();
}
int TcpServer::startServer()
{
m_socket = socket(AF_INET, SOCK_STREAM, 0);
if (m_socket < 0)
{
throw socketError("Cannot create socket");
}
int reuseAddress = 1;
if (setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &reuseAddress, sizeof(reuseAddress)) < 0)
{
throw socketError("Cannot set socket options");
}
m_sockAddress.sin_family = AF_INET;
m_sockAddress.sin_port = htons(m_port);
if (inet_pton(AF_INET, m_ip_address.c_str(), &m_sockAddress.sin_addr) <= 0)
{
throw std::runtime_error("Invalid IP address: " + m_ip_address);
}
if (bind(m_socket, reinterpret_cast<sockaddr *>(&m_sockAddress), m_sockAddress_len) < 0)
{
throw socketError("Cannot bind socket");
}
if (listen(m_socket, CONNECTION_BACKLOG) < 0)
{
throw socketError("Cannot listen on socket");
}
std::ostringstream serverAddress;
serverAddress << "Listening on http://" << m_ip_address << ":" << m_port;
log(serverAddress.str());
return 0;
}
void TcpServer::startListen()
{
while (true)
{
sockaddr_in clientAddress{};
socklen_t clientAddressLength = sizeof(clientAddress);
const int clientSocket = accept(
m_socket,
reinterpret_cast<sockaddr *>(&clientAddress),
&clientAddressLength);
if (clientSocket < 0)
{
log("Failed to accept client connection: " + std::string(std::strerror(errno)));
continue;
}
std::thread(&TcpServer::handleClient, this, clientSocket).detach();
}
}
void TcpServer::handleClient(int clientSocket) const
{
char buffer[BUFFER_SIZE] = {};
const ssize_t bytesReceived = recv(clientSocket, buffer, sizeof(buffer) - 1, 0);
if (bytesReceived <= 0)
{
close(clientSocket);
return;
}
const std::string request(buffer, static_cast<std::size_t>(bytesReceived));
const std::string response = buildResponse(request);
send(clientSocket, response.c_str(), response.size(), 0);
close(clientSocket);
}
std::string TcpServer::buildResponse(const std::string &request) const
{
const bool isHealthCheck = request.rfind("GET /health ", 0) == 0;
const bool isHomePage = request.rfind("GET / ", 0) == 0;
const std::string body = isHealthCheck
? "OK\n"
: isHomePage
? "<html><body><h1>Simple C++ Web Server</h1><p>Hello from a multithreaded TCP server.</p></body></html>\n"
: "<html><body><h1>404 Not Found</h1></body></html>\n";
const std::string status = (isHealthCheck || isHomePage)
? "HTTP/1.1 200 OK"
: "HTTP/1.1 404 Not Found";
std::ostringstream response;
response << status << "\r\n"
<< "Content-Length: " << body.size() << "\r\n"
<< "Content-Type: " << (isHealthCheck ? "text/plain" : "text/html") << "\r\n"
<< "Connection: close\r\n"
<< "\r\n"
<< body;
return response.str();
}
void TcpServer::closeServer()
{
if (m_socket >= 0)
{
close(m_socket);
m_socket = -1;
}
}
} // namespace http