wiki:KeepAlive
Last modified 7 years ago Last modified on 03/12/10 12:44:51

Sending keepalive requests

Sending keepalive's is off by default.

The two APIs are:

/*
 * libssh2_keepalive_config()
 *
 * Set how often keepalive messages should be sent.  WANT_REPLY
 * indicates whether the keepalive messages should request a response
 * from the server.  INTERVAL is number of seconds that can pass
 * without any I/O, use 0 (the default) to disable keepalives.  To
 * avoid some busy-loop corner-cases, if you specify an interval of 1
 * it will be treated as 2.
 *
 * Note that non-blocking applications are responsible for sending the
 * keepalive messages using libssh2_keepalive_send().
 */
LIBSSH2_API void libssh2_keepalive_config (LIBSSH2_SESSION *session,
                                          int want_reply,
                                          unsigned interval);

/*
 * libssh2_keepalive_send()
 *
 * Send a keepalive message if needed.  SECONDS_TO_NEXT indicates how
 * many seconds you can sleep after this call before you need to call
 * it again.  Returns 0 on success, or LIBSSH2_ERROR_SOCKET_SEND on
 * I/O errors.
 */
LIBSSH2_API int libssh2_keepalive_send (LIBSSH2_SESSION *session,
                                       int *seconds_to_next);

If your application is blocking, to enable sending of keepalive requests, you just add a call like this:

 libssh2_keepalive_config (session, 1, 5);

This will send keepalive messages every 5 seconds, and the message that will be sent requests the server to respond to the message (because want_reply=1). That's it!

If your application is non-blocking, you need to first call libssh2_keepalive_config as above, but you also need to make sure you call libssh2_keepalive_send in your select loop and use its output as the maximum time to sleep in your select call. For example:

 while (1) {
     struct timeval tmout;
     int err = libssh2_keepalive_send(sess, &tmout.tv_sec);
     if (err) {
         // ...
     }
     tmout.tv_usec = 0;
     // set up fd_sets
     ev = select(..., &tmout);
     // handle events
 }