zhaojh329 / libuwsc

A Lightweight and fully asynchronous WebSocket client library based on libev
MIT License
289 stars 53 forks source link

cannot reconnect after error or close event and ev_break() #12

Closed andrewhodel closed 4 years ago

andrewhodel commented 4 years ago

If I call ev_break on error or close, cl will be re-created with uwsc_new()

If I start the client it works fine, if I kill the server and restart it then the client just keeps saying:

2020/01/06 17:40:26 (cclient.c:87) Start connect...
2020/01/06 17:40:26 (cclient.c:62) onerror:6: Connect timeout

What do I need to reset so that uwsc_new() will reconnect as if it hadn't before?

Here is the code I am using in the main() loop:

int main(int argc, char **argv)
{
    const char *url = "wss://dev.sundialcommunications.com:8550/ws";
    struct ev_loop *loop = EV_DEFAULT;
    int ping_interval = 10; /* second */
    static struct ev_timer timeout_watcher;

    uwsc_log_info("Libuwsc: %s\n", UWSC_VERSION_STRING);

    // reconnects when there is a disconnect or error
    while (1) {
    cl = uwsc_new(loop, url, ping_interval, NULL);
    if (!cl)
        return -1;

    uwsc_log_info("Start connect...\n");

    cl->onopen = uwsc_onopen;
    cl->onmessage = uwsc_onmessage;
    cl->onerror = uwsc_onerror;
    cl->onclose = uwsc_onclose;

    ev_timer_init (&timeout_watcher, timer_cb, 10, 10);
    ev_timer_start (loop, &timeout_watcher);

    ev_run(loop, 0);

    // it will get to here if ev_break is called

    free(cl);

    sleep(10);
    }

    return 0;
}
andrewhodel commented 4 years ago

The example has to be written like this (variable declarations inside while loop) to not fail and restart automatically:

int main(int argc, char **argv)
{

    // uwsc reconnects when there is a disconnect or error
    while (1) {

    authed_flag = 0;

        struct ev_loop *loop = EV_DEFAULT;
        int ping_interval = 10; /* second */
        static struct ev_timer timeout_watcher;

        uwsc_log_info("Libuwsc: %s\n", UWSC_VERSION_STRING);

    cl = uwsc_new(loop, root_address, ping_interval, NULL);
    if (!cl)
        continue;

    uwsc_log_info("Start connect...\n");

    cl->onopen = uwsc_onopen;
    cl->onmessage = uwsc_onmessage;
    cl->onerror = uwsc_onerror;
    cl->onclose = uwsc_onclose;

    ev_timer_init (&timeout_watcher, timer_cb, 10, 10);
    ev_timer_start (loop, &timeout_watcher);

    ev_run(loop, 0);

    // it will get to here if ev_break is called

    free(cl);

    }

    return 0;
}