-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpServer.cpp
More file actions
228 lines (191 loc) · 6.04 KB
/
Copy pathHttpServer.cpp
File metadata and controls
228 lines (191 loc) · 6.04 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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
#include "HttpServer.h"
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstring>
#include <iostream>
#include <sstream>
namespace {
constexpr const char* kBoundary = "camerawebframe";
const char* kIndexHtml =
"<!DOCTYPE html>\n"
"<html><head><title>camera-web</title>"
"<style>body{background:#111;margin:0;display:flex;align-items:center;"
"justify-content:center;height:100vh}img{max-width:100%;max-height:100%}</style>"
"</head><body><img src=\"/stream\"></body></html>\n";
}
HttpServer::HttpServer(int port) : port_(port) {}
HttpServer::~HttpServer()
{
stop();
}
bool HttpServer::start()
{
listenFd_ = socket(AF_INET, SOCK_STREAM, 0);
if (listenFd_ < 0)
{
std::cerr << "[HttpServer] socket() failed: " << strerror(errno) << "\n";
return false;
}
int opt = 1;
setsockopt(listenFd_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(static_cast<uint16_t>(port_));
if (bind(listenFd_, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0)
{
std::cerr << "[HttpServer] bind() failed on port " << port_ << ": " << strerror(errno) << "\n";
close(listenFd_);
listenFd_ = -1;
return false;
}
if (listen(listenFd_, 16) < 0)
{
std::cerr << "[HttpServer] listen() failed: " << strerror(errno) << "\n";
close(listenFd_);
listenFd_ = -1;
return false;
}
running_ = true;
acceptThread_ = std::thread(&HttpServer::acceptLoop, this);
std::cerr << "[HttpServer] listening on http://0.0.0.0:" << port_ << "\n";
return true;
}
void HttpServer::stop()
{
if (!running_) return;
running_ = false;
if (listenFd_ >= 0)
{
shutdown(listenFd_, SHUT_RDWR);
close(listenFd_);
listenFd_ = -1;
}
frameCv_.notify_all();
if (acceptThread_.joinable())
acceptThread_.join();
}
void HttpServer::pushFrame(std::vector<uint8_t> jpegData)
{
{
std::lock_guard<std::mutex> lock(frameMutex_);
latestFrame_ = std::move(jpegData);
++frameId_;
}
frameCv_.notify_all();
}
void HttpServer::acceptLoop()
{
while (running_)
{
sockaddr_in clientAddr{};
socklen_t clientLen = sizeof(clientAddr);
int clientFd = accept(listenFd_, reinterpret_cast<sockaddr*>(&clientAddr), &clientLen);
if (clientFd < 0)
{
if (running_)
std::cerr << "[HttpServer] accept() failed: " << strerror(errno) << "\n";
continue;
}
int nodelay = 1;
setsockopt(clientFd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay));
std::thread(&HttpServer::handleClient, this, clientFd).detach();
}
}
bool HttpServer::sendAll(int fd, const char* data, size_t len)
{
size_t sent = 0;
while (sent < len)
{
ssize_t n = send(fd, data + sent, len - sent, MSG_NOSIGNAL);
if (n <= 0)
return false;
sent += static_cast<size_t>(n);
}
return true;
}
void HttpServer::handleClient(int clientFd)
{
// Read (and discard) the request line / headers - we only care about
// the path, and only support GET / and GET /stream.
char buf[2048];
ssize_t n = recv(clientFd, buf, sizeof(buf) - 1, 0);
if (n <= 0)
{
close(clientFd);
return;
}
buf[n] = '\0';
std::string request(buf);
std::string path = "/";
{
size_t methodEnd = request.find(' ');
size_t pathEnd = request.find(' ', methodEnd + 1);
if (methodEnd != std::string::npos && pathEnd != std::string::npos)
path = request.substr(methodEnd + 1, pathEnd - methodEnd - 1);
}
if (path == "/" || path == "/index.html")
{
std::ostringstream header;
header << "HTTP/1.1 200 OK\r\n"
<< "Content-Type: text/html\r\n"
<< "Content-Length: " << strlen(kIndexHtml) << "\r\n"
<< "Connection: close\r\n\r\n";
sendAll(clientFd, header.str().c_str(), header.str().size());
sendAll(clientFd, kIndexHtml, strlen(kIndexHtml));
close(clientFd);
return;
}
if (path != "/stream")
{
static const char* notFound =
"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
sendAll(clientFd, notFound, strlen(notFound));
close(clientFd);
return;
}
std::ostringstream header;
header << "HTTP/1.1 200 OK\r\n"
<< "Cache-Control: no-cache, private\r\n"
<< "Pragma: no-cache\r\n"
<< "Content-Type: multipart/x-mixed-replace; boundary=" << kBoundary << "\r\n"
<< "Connection: close\r\n\r\n";
if (!sendAll(clientFd, header.str().c_str(), header.str().size()))
{
close(clientFd);
return;
}
clientCount_++;
std::cerr << "[HttpServer] client connected (" << clientCount_.load() << " active)\n";
uint64_t lastFrameId = 0;
bool ok = true;
while (running_ && ok)
{
std::vector<uint8_t> frame;
{
std::unique_lock<std::mutex> lock(frameMutex_);
frameCv_.wait(lock, [&] {
return !running_ || frameId_ != lastFrameId;
});
if (!running_)
break;
frame = latestFrame_;
lastFrameId = frameId_;
}
std::ostringstream part;
part << "--" << kBoundary << "\r\n"
<< "Content-Type: image/jpeg\r\n"
<< "Content-Length: " << frame.size() << "\r\n\r\n";
ok = sendAll(clientFd, part.str().c_str(), part.str().size());
if (ok)
ok = sendAll(clientFd, reinterpret_cast<const char*>(frame.data()), frame.size());
if (ok)
ok = sendAll(clientFd, "\r\n", 2);
}
close(clientFd);
clientCount_--;
std::cerr << "[HttpServer] client disconnected (" << clientCount_.load() << " active)\n";
}