使用libstrophe,我可以在连接断开时自动重新连接。 我在客户端使用了以下代码:
<form>
<div class="question">
<header>What's a women called whom lost 90% of her intelligence?</header>
<label><input type="radio" name="question_1" value="a" checked><span>Apple</span></label>
<label><input type="radio" name="question_1" value="b"><span>Widow</span></label>
<label><input type="radio" name="question_1" value="c"><span>Nurse</span></label>
</div>
<div class="question">
<header>How do you call a man who lost 90% of his intelligence?</header>
<label><input type="radio" name="question_2" value="a"><span>Blue</span></label>
<label><input type="radio" name="question_2" value="b"><span>Plumber</span></label>
<label><input type="radio" name="question_2" value="c"><span>Divorced</span></label>
</div>
</form>
当客户端第一次连接时,我收到消息“DEBUG:connected” 服务器完成后,我收到消息“DEBUG:disconnected”。但是当服务器第二次启动时,客户端不会自动重新连接。
答案 0 :(得分:0)
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;
}