Skip to content

Commit 461ff10

Browse files
committed
fix: refactor connection handling with improved success and failure callbacks
Signed-off-by: Dengfeng Liu <[email protected]>
1 parent 0d96d26 commit 461ff10

File tree

2 files changed

+45
-24
lines changed

2 files changed

+45
-24
lines changed

control.c

Lines changed: 42 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -639,33 +639,51 @@ recv_cb(struct bufferevent *bev, void *ctx)
639639
return;
640640
}
641641

642-
static void
643-
connect_event_cb (struct bufferevent *bev, short what, void *ctx)
642+
static void handle_connection_failure(struct common_conf *c_conf, int *retry_times) {
643+
debug(LOG_ERR, "Connection to server [%s:%d] failed: %s",
644+
c_conf->server_addr,
645+
c_conf->server_port,
646+
strerror(errno));
647+
648+
(*retry_times)++;
649+
if (*retry_times >= MAX_RETRY_TIMES) {
650+
debug(LOG_INFO, "Maximum retry attempts (%d) reached", MAX_RETRY_TIMES);
651+
}
652+
653+
sleep(RETRY_DELAY_SECONDS);
654+
655+
reset_session_id();
656+
clear_main_control();
657+
run_control();
658+
}
659+
660+
static void handle_connection_success(struct bufferevent *bev) {
661+
debug(LOG_INFO, "Successfully connected to xfrp server");
662+
663+
// Initialize window and login
664+
send_window_update(bev, &main_ctl->stream, 0);
665+
login();
666+
667+
// Setup keepalive mechanism
668+
keep_control_alive();
669+
}
670+
671+
static void connect_event_cb(struct bufferevent *bev, short what, void *ctx)
644672
{
645-
struct common_conf *c_conf = get_common_config();
646-
static int retry_times = 1;
673+
static int retry_times = 0;
674+
struct common_conf *c_conf = get_common_config();
675+
676+
if (!c_conf) {
677+
debug(LOG_ERR, "Failed to get common config");
678+
return;
679+
}
680+
647681
if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
648-
if (retry_times >= 100) {
649-
debug(LOG_INFO,
650-
"have retry connect to xfrp server for %d times, exit?",
651-
retry_times);
652-
}
653-
sleep(2);
654-
retry_times++;
655-
debug(LOG_ERR, "error: connect server [%s:%d] failed %s",
656-
c_conf->server_addr,
657-
c_conf->server_port,
658-
strerror(errno));
659-
reset_session_id();
660-
clear_main_control();
661-
run_control();
662-
} else if (what & BEV_EVENT_CONNECTED) {
663-
debug(LOG_DEBUG, "xfrp server connected");
682+
handle_connection_failure(c_conf, &retry_times);
683+
}
684+
else if (what & BEV_EVENT_CONNECTED) {
664685
retry_times = 0;
665-
send_window_update(bev, &main_ctl->stream, 0);
666-
login();
667-
668-
keep_control_alive();
686+
handle_connection_success(bev);
669687
}
670688
}
671689

control.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@
2222
#include "msg.h"
2323
#include "uthash.h"
2424

25+
#define MAX_RETRY_TIMES 100
26+
#define RETRY_DELAY_SECONDS 2
27+
2528
/**
2629
* @brief Main control structure for FRP client
2730
*/

0 commit comments

Comments
 (0)