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
| #include "lib_acl.h" #include "fiber/lib_fiber.h" #include "acl_cpp/lib_acl.hpp"
class http_servlet : public acl::HttpServlet { public: http_servlet(acl::socket_stream* stream, acl::session* session) : HttpServlet(stream, session) { }
~http_servlet(void) { }
bool doGet(acl::HttpServletRequest& req, acl::HttpServletResponse& res) { return doPost(req, res); }
bool doPost(acl::HttpServletRequest&, acl::HttpServletResponse& res) { const char* buf = "hello world!"; size_t len = strlen(buf);
res.setContentLength(len); res.setKeepAlive(true);
return res.write(buf, len) && res.write(NULL, 0); } };
#define STACK_SIZE 320000 static int __rw_timeout = 0;
static void http_server(ACL_FIBER *, void *ctx) { acl::socket_stream *conn = (acl::socket_stream *) ctx;
printf("start one http_server\r\n");
acl::memcache_session session("127.0.0.1:11211");
http_servlet servlet(conn, &session); servlet.setLocalCharset("gb2312");
while (true) { if (servlet.doRun() == false) break; }
printf("close one connection: %d, %s\r\n", conn->sock_handle(), acl::last_serror());
delete conn; }
static void fiber_accept(ACL_FIBER *, void *ctx) { const char* addr = (const char* ) ctx; acl::server_socket server;
if (server.open(addr) == false) { printf("open %s error\r\n", addr); exit (1); } else printf("open %s ok\r\n", addr);
while (true) { acl::socket_stream* client = server.accept(); if (client == NULL) { printf("accept failed: %s\r\n", acl::last_serror()); break; }
client->set_rw_timeout(__rw_timeout); printf("accept one: %d\r\n", client->sock_handle());
acl_fiber_create(http_server, client, STACK_SIZE); }
exit (0); }
static void usage(const char* procname) { printf("usage: %s -h [help] -s listen_addr -r rw_timeout\r\n", procname); }
int main(int argc, char *argv[]) { acl::string addr("127.0.0.1:9001"); int ch;
while ((ch = getopt(argc, argv, "hs:r:")) > 0) { switch (ch) { case 'h': usage(argv[0]); return 0; case 's': addr = optarg; break; case 'r': __rw_timeout = atoi(optarg); break; default: break; } }
acl::acl_cpp_init(); acl::log::stdout_open(true);
acl_fiber_create(fiber_accept, addr.c_str(), STACK_SIZE);
acl_fiber_schedule();
return 0; }
|