Skip to content

Commit 74432b9

Browse files
committed
Move the connection on which we received the new request to the end of the connected_clients list. This works like LRU.
1 parent cb3f5b5 commit 74432b9

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

src/httpserver.cpp

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,16 @@ static request_callback_t request_callback = NULL;
1616
static std::list<client_t*> connected_clients;
1717
static const int MAX_CONNECTED_CLIENTS = 900;
1818
static int nconnected_clients = 0;
19+
static std::list<client_t*> empty_list; // Used to move nodes around in O(1) time by move_to_back().
20+
21+
// Move element pointed to by 'iter' to the end of the list
22+
// 'l'. 'iter' MUST be a member of 'l'.
23+
void move_to_back(std::list<client_t*> &l, std::list<client_t*>::iterator iter) {
24+
assert(empty_list.empty());
25+
assert(!l.empty());
26+
empty_list.splice(empty_list.end(), l, iter);
27+
l.splice(l.end(), empty_list, empty_list.begin());
28+
}
1929

2030
void build_HTTP_response_header(std::string &response_header,
2131
int http_major, int http_minor,
@@ -25,12 +35,13 @@ void build_HTTP_response_header(std::string &response_header,
2535
response_header.clear();
2636
std::ostringstream os;
2737
char buff[2048];
38+
// Ensure that status_str is small enough that everything fits in under 2048 bytes.
2839
sprintf(buff, "HTTP/%d.%d %d %s\r\n", http_major, http_minor, status_code, status_str);
2940
os<<buff;
3041
sprintf(buff, "%d", body.size());
3142
headers["Content-Length"] = buff;
3243
headers["Connection"] = "Keep-alive";
33-
for (headers_t::const_iterator i = headers.begin();
44+
for (headers_t::iterator i = headers.begin();
3445
i != headers.end(); ++i) {
3546
os<<i->first<<": "<<i->second<<"\r\n";
3647
}
@@ -168,7 +179,7 @@ void parse_query_string(std::string &qstr, query_strings_t &query) {
168179
for (size_t i = 0; i < qstr.size(); ++i) {
169180
char ch = qstr[i];
170181
if (ch == '&') {
171-
query[key] = value;
182+
query[key].swap(value);
172183
key.clear();
173184
value.clear();
174185
parsing_key = true;
@@ -183,7 +194,7 @@ void parse_query_string(std::string &qstr, query_strings_t &query) {
183194
}
184195
}
185196
if (!key.empty()) {
186-
query[key] = value;
197+
query[key].swap(value);
187198
}
188199
}
189200

@@ -222,6 +233,9 @@ int on_message_complete(http_parser* parser) {
222233

223234
uv_read_stop(pstrm);
224235

236+
// Move to back.
237+
move_to_back(connected_clients, client->cciter);
238+
225239
// Invoke callback.
226240
request_callback(client);
227241
return 1;

0 commit comments

Comments
 (0)