我正在使用apollo代理和mosquitto C客户端库。成功发布消息后,我使用mosquitto_disconnect(mosq)函数断开客户端连接。但看起来客户端用来与代理连接的端口仍然不是免费的。有没有办法在c程序中手动释放客户端用来连接代理的端口?
void on_publish(struct mosquitto *mosq, void *userdata, int mid)
{
mosquitto_disconnect(mosq);
log_print("mqtt",1,"Inside publish callback");
}
int sendData_mqtt(char *address, char *port, char* url, char *data)
{
struct mosquitto *mosq;
int err;
char *clean_session = "true";
char *retain_flag = "true";
int port1= atoi(port);
mosq = mosquitto_new("unknown", clean_session, NULL);
mosquitto_publish_callback_set(mosq, on_publish);
mosquitto_username_pw_set(mosq,"admin","password");
err=mosquitto_connect(mosq, address,port1,60);
if(err != 0 ){
log_print("mqtt",1,"connect error= %s\n",mosquitto_strerror(err));
return -1;
}
else
log_print("mqtt",1,"successfully connected");
err = mosquitto_publish(mosq, NULL, "subject", strlen(data), data, 1, retain_flag);
sleep(5);
if(err != 0 ) {
log_print("mqtt",1,"Publish error = %s\n",mosquitto_strerror(err));
return -1;
}
mosquitto_loop_forever(mosq,-1,1);
return 10;
}
答案 0 :(得分:0)
这应该会自动发生,一旦libmosquitto认为已发送DISCONNECT数据包,它将关闭套接字。
您是否已调用mosquitto_loop_forever()或mosquitto_loop_start()以处理网络流量?
您使用的是什么版本的libmosquitto?
可能是经纪人在没有意识到的情况下拒绝您的凭据吗?尝试添加日志回调以查看发生的情况。
void on_log(struct mosquitto *mosq, void *userdata, int level, const char *msg)
{
printf("%s\n", msg);
}
并使用
mosquitto_log_callback_set(mosq, on_log);
我很想说你还需要回归基础。查看clean_session并保留mosquitto_new和mosquitto_publish的参数 - 它们不应该是char *
字符串设置为“true”。阅读文档,了解可用于调试的工具(例如on_log)然后离开并进行一些调试。也许查看来源,看看你期望发生什么。