1 #include <stdlib.h>
2 #include <unistd.h>
3 #include <fstream>
4 #include <algorithm>
5
6 #include <http/webservertask.h>
7 #include <framework/eventloop.h>
8
9 /* Example 009
10
11 Create two threads, each running a WebServer in its own eventloop.
12 One will listen on port 8000, the other on 8080. To test, open URLs
13
14 http://127.0.0.1:8000/getTime
15 http://127.0.0.1:8080/getTime
16 http://127.0.0.1:8000/getStats
17 http://127.0.0.1:8080/getStats
18 http://127.0.0.1:8000/stop
19 http://127.0.0.1:8080/stop
20
21 in a web browser. The /stop URL will tell each server to exit. The test program
22 will exit when both servers have been stopped.
23
24 */
25
26 class WebServer : public WebServerTask {
27 public:
WebServer(const std::string & cfg,const std::string & name)28 WebServer(const std::string &cfg, const std::string &name) :
29 WebServerTask(name, cfg) {
30 }
31
32 HttpState newGetRequest(HttpServerConnection *,
33 const std::string &uri) override;
34 private:
35 unsigned long tot_no_requests = 0;
36 };
37
newGetRequest(HttpServerConnection * conn,const std::string & uri)38 HttpState WebServer::newGetRequest(HttpServerConnection *conn,
39 const std::string &uri) {
40 ++tot_no_requests;
41 log() << "URI: " << uri << " #" << tot_no_requests;
42 if (uri == "/getTime")
43 conn->sendHttpResponse(headers("200 OK"), "text/plain", dateString());
44 else if (uri == "/getStats")
45 conn->sendHttpResponse(headers("200 OK"), "text/plain",
46 std::to_string(tot_no_requests));
47 else if (uri == "/stop")
48 setResult("DONE");
49 else
50 conn->sendHttpResponse(headers("404 Not Found"), "text/plain",
51 "unknown service");
52 return HttpState::WAITING_FOR_REQUEST;
53 }
54
main(int,char * [])55 int main(int , char *[]) {
56 std::ofstream my_log("main.log"), log1("M8000.log"), log2("M8080.log");
57 Logger::setLogFile(my_log);
58 EventLoop loop;
59 loop.spawnThread(new WebServer("listen 8000", "W8000"), "M8000", &log1);
60 loop.spawnThread(new WebServer("listen 8080", "W8080"), "M8080", &log2);
61 loop.runUntilComplete();
62 return 0;
63 }
64