Skip to content

支持 http 服务绑定 onAccept 和 onClose 回调 #717

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions http/server/HttpHandler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ HttpHandler::HttpHandler(hio_t* io) :
tid(0),
// for http
io(io),
server(NULL),
service(NULL),
api_handler(NULL),
// for websocket
Expand Down
1 change: 1 addition & 0 deletions http/server/HttpHandler.h
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ class HttpHandler {

// for http
hio_t *io;
void *server;
HttpService *service;
HttpRequestPtr req;
HttpResponsePtr resp;
Expand Down
17 changes: 14 additions & 3 deletions http/server/HttpServer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,17 @@ static void on_recv(hio_t* io, void* buf, int readbytes) {
static void on_close(hio_t* io) {
HttpHandler* handler = (HttpHandler*)hevent_userdata(io);
if (handler == NULL) return;

hevent_set_userdata(io, NULL);
delete handler;
http_server_t* server = (http_server_t*)handler->server;

EventLoop* loop = currentThreadEventLoop;
if (loop) {
if (server->onClose) {
server->onClose(io);
}
--loop->connectionNum;
}
hevent_set_userdata(io, NULL);
delete handler;
}

static void on_accept(hio_t* io) {
Expand All @@ -65,6 +68,12 @@ static void on_accept(hio_t* io) {
hio_close(io);
return;
}
if (server->onAccept) {
if (!server->onAccept(io)) {
hio_close(io);
return;
}
}
++loop->connectionNum;

hio_setcb_close(io, on_close);
Expand All @@ -82,6 +91,8 @@ static void on_accept(hio_t* io) {
sockaddr_u* peeraddr = (sockaddr_u*)hio_peeraddr(io);
sockaddr_ip(peeraddr, handler->ip, sizeof(handler->ip));
handler->port = sockaddr_port(peeraddr);
// http server
handler->server = server;
// http service
handler->service = service;
// websocket service
Expand Down
2 changes: 2 additions & 0 deletions http/server/HttpServer.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ typedef struct http_server_s {
// hooks
std::function<void()> onWorkerStart;
std::function<void()> onWorkerStop;
std::function<bool(hio_t* io)> onAccept;
std::function<void(hio_t* io)> onClose;
// SSL/TLS
hssl_ctx_t ssl_ctx;
unsigned alloced_ssl_ctx: 1;
Expand Down