-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpserver.cpp
More file actions
111 lines (90 loc) · 1.9 KB
/
httpserver.cpp
File metadata and controls
111 lines (90 loc) · 1.9 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
// httpserver.cpp
#include "httpserver.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <iostream>
using namespace std;
HttpServer::HttpServer(int port, int threads) : running(false), port(port), num_threads(threads)
{
}
bool HttpServer::start()
{
running = true;
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0)
{
return false;
}
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
int opt = 1;
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
if (bind(server_fd, (sockaddr *)&addr, sizeof(addr)) < 0)
{
return false;
}
if (listen(server_fd, 128) < 0)
{
return false;
}
accept_thread = thread(&HttpServer::accept_loop, this);
for (int i = 0; i < num_threads; i++)
{
workers.emplace_back(&HttpServer::worker_loop, this);
}
return true;
}
void HttpServer::accept_loop()
{
while (running)
{
int client_fd = accept(server_fd, nullptr, nullptr);
if (client_fd < 0)
continue;
char buffer[4096];
int bytes = read(client_fd, buffer, sizeof(buffer) - 1);
buffer[bytes] = '\0';
Request r;
r.client_fd = client_fd;
r.data = buffer;
q.push(r);
}
}
void HttpServer::worker_loop()
{
while (running)
{
Request r = q.pop();
handle_request(r.data, r.client_fd);
}
}
void HttpServer::handle_request(const string &req, int client_fd)
{
string response =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: 13\r\n"
"\r\n"
"Hello, world";
int x = 0;
for (int i = 0; i < 5000000; i++)
{
x += i;
}
send(client_fd, response.c_str(), response.size(), 0);
close(client_fd);
}
void HttpServer::stop()
{
running = false;
close(server_fd);
accept_thread.join();
for (auto &t : workers)
{
t.join();
}
}