Libstrophe 不会自动重新连接。从 libstrophe-0.9.0 开始,xmpp_conn_t
可以重新连接对象,而不会丢失登录信息和用户处理程序:
#include <stdio.h>
#include <strophe.h>
void conn_handler(xmpp_conn_t * const conn, const xmpp_conn_event_t status,
const int error, xmpp_stream_error_t * const stream_error,
void * const userdata)
{
if (status == XMPP_CONN_CONNECT) {
fprintf(stderr, "DEBUG: connected\n");
} else {
fprintf(stderr, "DEBUG: disconnected, reconnecting...\n");
xmpp_connect_client(conn, NULL, 0, conn_handler, userdata);
}
}
int main()
{
xmpp_log_t *log;
xmpp_ctx_t *ctx;
xmpp_conn_t *conn;
const char *jid = "test@domain.com";
const char *pass = "password";
xmpp_initialize();
log = xmpp_get_default_logger(XMPP_LEVEL_ERROR);
ctx = xmpp_ctx_new(NULL, log);
conn = xmpp_conn_new(ctx);
xmpp_conn_set_jid(conn, jid);
xmpp_conn_set_pass(conn, pass);
xmpp_connect_client(conn, NULL, 0, conn_handler, NULL);
xmpp_run(ctx);
xmpp_conn_release(conn);
xmpp_ctx_free(ctx);
xmpp_shutdown();
return 0;
}
在 0.9.0 之前的版本中,用户无法xmpp_conn_t
在断开连接后重用对象,需要创建新对象。libstrophe-0.8.8 及更早版本的示例:
#include <stdio.h>
#include <strophe.h>
#define TIMEOUT 1000
void conn_handler(xmpp_conn_t * const conn, const xmpp_conn_event_t status,
const int error, xmpp_stream_error_t * const stream_error,
void * const userdata)
{
int *reconnect = userdata;
if (status == XMPP_CONN_CONNECT) {
fprintf(stderr, "DEBUG: connected\n");
} else {
fprintf(stderr, "DEBUG: disconnected, reconnecting...\n");
*reconnect = 1;
}
}
int main()
{
xmpp_log_t *log;
xmpp_ctx_t *ctx;
xmpp_conn_t *conn;
const char *jid = "test@domain.com";
const char *pass = "password";
int reconnect;
xmpp_initialize();
log = xmpp_get_default_logger(XMPP_LEVEL_ERROR);
ctx = xmpp_ctx_new(NULL, log);
while (1) {
conn = xmpp_conn_new(ctx);
xmpp_conn_set_jid(conn, jid);
xmpp_conn_set_pass(conn, pass);
xmpp_connect_client(conn, NULL, 0, conn_handler, &reconnect);
reconnect = 0;
while (!reconnect)
xmpp_run_once(ctx, TIMEOUT);
xmpp_conn_release(conn);
}
xmpp_ctx_free(ctx);
xmpp_shutdown();
return 0;
}