So I'm trying to send more than a file from my server side to the client .I have already completed the task of sending one file with its size. To explain more the name of the file is passed as argument to the client then send to the server to check if there is a file with this name in the shared folder by the server, if yes then the server sends the file to the client.
My idea was send the number of files to be sent to the client then do the same stuff I do for one single file in for loop but the cold crush I don't now why.
And I also try to connect using wifi in 2 different PC but the code does it work correctly, I test it before using ethernet cable and all go ok
Can any one help me please?
this link to the project folder :
https://github.com/amaraoussama94/Server_Client-C-app
i try some video youtube and some other solution but it crush
i expect to have some idea , or code to boost me
Snap of project :
server :
#include <arpa/inet.h> // inet_addr()/
#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>//system
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h> // read(), write(), close()
#include <errno.h>
#include "Const.h"
#include "arg_test.h"
#include <time.h>//get time and date for log file
#include <string.h>//
//void* SendFileToClient(int *arg)
void SendFileToClient(int *ptr_connfd,char * fname ,struct sockaddr_in cli )
{
//int connfd=(int)*arg;
printf("[i]Connection accepted and id: %d\n",*ptr_connfd);
printf("[i]Connected to Clent: %s:%d\n",inet_ntoa(cli.sin_addr),ntohs(cli.sin_port));
write(*ptr_connfd, fname,256);
FILE *fp = fopen(fname,"rb");
if(fp==NULL)
{
printf("\033[0;31m");
printf("[-]File for transfer open error\n");
printf("\033[0m");
exit(1);
}
/*******************************************/
fseek(fp, 0L, SEEK_END);
// calculating the size of the file
long int res = ftell(fp);
//conver to char to send it
char size[10];
sprintf(size, "%f", (res/1024.0) );
//send file size to the client
write(*ptr_connfd, size, sizeof(size));
printf("[i]size of the file to transfer is %f Kb\n",(res/1024.0));
fseek(fp, 0, SEEK_SET);
/******************************************/
/* Read data from file and send it */
while(1)
{
/* First read file in chunks of 256 bytes */
unsigned char buff[1024]={0};
int nread = fread(buff,1,1024,fp);
//printf("Bytes read %d \n", nread);
/* If read was success, send data. */
if(nread > 0)
{
//printf("Sending \n");
write(*ptr_connfd, buff, nread);
}
if (nread < 1024)
{
if (feof(fp))
{
// printf("End of file\n");
printf("\033[0;32m");
printf("[+]File transfer completed for id: %d\n",*ptr_connfd);
printf("\033[0m");
}
if (ferror(fp))
{
printf("\033[0;31m");
printf("[-]Error reading file for transfer \n");
printf("\033[0m");
}
break;
}
}
printf("\033[0;32m");
printf("[+]Closing Connection for id: %d\n",*ptr_connfd);
printf("\033[0;31m");
close(*ptr_connfd);
//shutdown(*ptr_connfd,SHUT_WR);
sleep(2);
}
// Function designed for chat between client and server.
int share_msg(int* ptr_connfd,char **argv ,struct sockaddr_in cli,int *ptr_change )
{
FILE *filePointer,*filePointerTransfer ;
char cmd [100]="./script.sh ";
char buff[MAX];
char string[MAX];
int Exist =0 ;
int j =0;
int err ;
pthread_t tid;
// bzero :Set N bytes of pointer to 0.
bzero(buff, MAX);//or you can use memset (&buff,'\0',sizeof(buff))
// read the message from client and copy it in buffer
read(*ptr_connfd, buff, sizeof(buff));
// print buffer which contains the client contents
if (strncmp("bash_list", buff, 9) == 0)
{ printf("[i]The client wants information about shared folder\n ");
//| awk '{print $1 " " $11 }' " " : field are sparate with space , $1 et $ 11 print colom1 and 11
//chdir(argv[4]);// change the path
strcat(cmd,argv[4]);
//int status = system("ls -al|awk '{print $1 " " $11}' > cmdoutput" );
int status = system(cmd);
//open file
filePointer = fopen("stdout.txt", "r");
//ste the psotion of the pointer at the bening of the file
if (filePointer == NULL)
{
printf("\033[0;31m");
printf("[-]Error can t find list of file to share \n");
printf("\033[0m");
bzero(buff,sizeof(buff));
strcat(buff,"ERRORFILE1");
write(*ptr_connfd, buff, sizeof(buff));
exit(1);
}
fseek(filePointer, 0, SEEK_SET);
while(fgets(buff, MAX, filePointer))
{
// send that buffer to clients
if (strncmp(buff ,".",1)==0 || strncmp(buff ,"..",2)==0 || strncmp(buff ,"/",1)==0)
{
continue;
}
write(*ptr_connfd, buff, sizeof(buff));
}
bzero(buff, MAX);
for(int j =0 ;j<sizeof(buff);j++)
{
buff[j] = '#';
}
//send to client
write(*ptr_connfd, buff, sizeof(buff));
//file
fclose(filePointer);
return 1;
}
else if (strcmp("bash_Transf", buff) == 0)
{
int num_file ;
//get numlber of file to send
bzero(buff, MAX);
read(*ptr_connfd, buff, sizeof(buff));
sscanf(buff,"%d",&num_file);
printf("[i] the number of file to send to the client is %d\n",num_file);
//get file name
bzero(buff, MAX);
read(*ptr_connfd, buff, sizeof(buff));
printf("the file name is %s \n",buff);
/*********************************************///must change dir if it run 2nd it crush
char path[100] ;
//get the current dir path
if (*ptr_change)
{
getcwd(path, sizeof(path)) ;
}
*ptr_change =0 ;
int dir_test = chdir(path);
//printf(" hello dir_test =%d and path=%s\n",dir_test,path);
//system("pwd");//test to check dir path
/********************************************/
filePointer = fopen("stdout.txt", "r");
if (filePointer == NULL)
{
printf("\033[0;31m");
printf("[-]Error can t find list of file to share \n");
printf("\033[0m");
exit(1);
}
//get iof the file name existt or no in the shared folder
while ( fgets( string ,MAX, filePointer) )// fscanf(filePointer,"%s", string) == 1
{
//lets take out the \n introduce by fgets
string[strcspn(string,"\n")]= 0;
if (strcmp(string,buff)==0)
{
Exist = 1;
break;
}
}
if (Exist)
{
fclose(filePointer);
//transfer file here
chdir(argv[4]);// change the path
printf( "[i]the file for transfer name is = %s \n",buff);
SendFileToClient(ptr_connfd,buff ,cli );
//create thread for sending the file to the client
/*err = pthread_create(&tid, NULL, &SendFileToClient, ptr_connfd);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));*/
}
else
{
bzero(buff, sizeof(buff));
strcat(buff,"file_error");
write(*ptr_connfd, buff, sizeof(buff));
bzero(buff, sizeof(buff));
printf("\033[0;31m");
printf("[-] Client try to get file that doesn't exist in the shared folder \n");
printf("\033[0m");
}
// si il n y a aucun paramatere passe au clien ni t ni
// list le server se ferme par return 1 and close the while loop
return 1;
}
else
return 0;
}
void create_scoket(int * sockfd)
{
*sockfd = socket(AF_INET, SOCK_STREAM, 0);// AF_INET :IPV4 , SOCK_STREAM:TCP
if (sockfd < 0)
{
printf("\033[0;31m");
perror("[-]socket creation failed...\n");
printf("\033[0m");
exit(1);
}
else
{
printf("\033[0;32m");
printf("[+]Socket successfully created..\n");
printf("\033[0m");
}
}
void socket_bind(struct sockaddr_in *servaddr ,int * sockfd)
{
// Binding newly created socket to given IP and verification
if ((bind(*sockfd, (SA*)servaddr, sizeof(*servaddr))) < 0)
{
printf("\033[0;31m");
perror("[-]socket bind failed...\n");
printf("\033[0m");
exit(1);
}
else
{
printf("\033[0;32m");
printf("[+]Socket successfully binded..\n");
printf("\033[0m");
}
}
void socket_listening (int *sockfd)
{
if ((listen(*sockfd, LISTENQ)) != 0) //5 connection requests will be queued before further requests are refused.
{
printf("\033[0;31m");
printf("[-]Listen failed...\n");
printf("\033[0m");
exit(1);
}
else
{
printf("\033[0;32m");
printf("[+]Server listening..\n");
printf("\033[0m");
}
}
void socket_accept (int *connfd , int* sockfd ,struct sockaddr_in*cli , int *len)
{
*connfd = accept(*sockfd, (SA*)cli, len);
if (connfd < 0)
{
printf("\033[0;31m");
perror("[-]server accept failed...\n");
printf("\033[0m");
exit(1);
}
else
{
printf("\033[0;32m");
printf("[+]server accept the client...\n");
printf("\033[0m");
}
}
// Driver function
int main(int argc, char **argv)
{
//for socket
int sockfd, connfd, len;
int *ptr_sockfd ,*ptr_connfd , *ptr_len;
struct sockaddr_in servaddr, cli;
struct sockaddr_in *ptr_servaddr , *ptr_cli;
int change =1 ; //for transfer
int *ptr_change =&change;
check_arg_server(argc,argv);
// socket create and verification
ptr_sockfd = &sockfd;
create_scoket(ptr_sockfd);
//initialize to zeo
// bzero :Set N bytes of pointer to 0.
bzero(&servaddr, sizeof(servaddr));//or you can use memset (&servaddr,'\0', sizeof(servaddr))
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr =htonl(INADDR_ANY);// Address to accept any incoming messages.
servaddr.sin_port = htons(atoi(argv[2]));//htons :Functions to convert between host and network byte order
//binding
ptr_servaddr = &servaddr;
socket_bind(ptr_servaddr ,ptr_sockfd);
// Now server is ready to listen and verification
socket_listening (ptr_sockfd);
//chek for ctr+z as input to stope server
while (1)
{
len = sizeof(cli);
//printf("hello ok \n");
// Accept the data packet from client and verification
ptr_connfd = &connfd;
ptr_len = &len;
ptr_cli= &cli ;
socket_accept (ptr_connfd , ptr_sockfd , ptr_cli , ptr_len);
//temp sol to stop server
int b = share_msg(ptr_connfd,argv,cli,ptr_change);
if (!b)
{
close(connfd);
break;
}
close(connfd);
sleep(1);
}
// After chatting close the socket
close(sockfd);
printf("[i] Server will Shutdown \n");
return 0;
}
client :
#include <arpa/inet.h> // inet_addr()/
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h> // bzero()
#include <sys/socket.h>
#include <unistd.h> // read(), write(), close()
#include "Const.h"
#include "arg_test.h"
// for mkdir function
#include <sys/stat.h>
#include <sys/types.h>
const int PROG_BAR_LENGTH =30 ;//30 caractere
void update_bar(float percent_done )
{
int num_car =(int) percent_done * PROG_BAR_LENGTH / 100 ;//number of caractere to print
printf(" \r[");
for(int i =0;i<num_car;i++)
{
printf("\033[0;32m"); //Set the text to the color Green
printf("■");
}
for(int i =0;i<(PROG_BAR_LENGTH -num_car);i++) //unfinish part of progress bar
{
printf(" ");
}
if((int)percent_done > 100)
{
percent_done =100 ;
}
printf("\033[0m"); //Resets the text to default color
printf("] %d%% Done.",(int)percent_done );
// fflush(stdout);//print all to the screen
}
void share_msg(int *sockfd,char ** argv, int argc)
{
char buff[MAX]="bash";
char msg[MAX];
FILE *filetransferPointer;
int n , bytesReceived = 0 ;
if (strcmp("--list", argv[5]) == 0)
{
strcat(buff,"_list");
}
if (strcmp("-T", argv[5]) == 0)
{
strcat(buff,"_Transf");
}
//send to server
write(*sockfd, buff, sizeof(buff));
bzero(buff, sizeof(buff));
if (strcmp("--list", argv[5]) == 0)
{
//read receive msg from server
read(*sockfd, msg, sizeof(msg));
read(*sockfd, msg, sizeof(msg));
if(!strcmp(msg,"ERRORFILE1"))
{
printf("[-] Error server can t list file \n ");
exit(1);
}
printf("[i]This is the list of file and folder shared by the server : \n These are the directories : \n" );
while(1)
{
read(*sockfd, msg, sizeof(msg));
if(!strncmp(msg, "#", 1) )
{
break;
}
printf("%s \n ",msg);
}
}
else if (strcmp("-T", argv[5]) == 0)
{
//get number of file to receive from server
int num_file = argc-6;
bzero(msg, sizeof(msg));
sprintf(msg,"%d",num_file);
write(*sockfd, msg, sizeof(msg));
//printf ("num = %s\n",msg);
//send file name to server
bzero(msg, sizeof(msg));
strcat(msg,argv[6]);
printf(" the buff is = %s",msg);
write(*sockfd, msg, sizeof(msg));
//check if the file name exist or no
bzero(msg, sizeof(msg));
read(*sockfd, msg, sizeof(msg));
if (strcmp(msg,"file_error")==0)
{ printf("\033[0;31m");
printf("[-]Please try again ,maybe try --list first then try again ,or maybe no file has this name \n" );
printf("\033[0m");
exit(1);
}
//get the file
char* dirname = "transfer";
mkdir(dirname,0755);
//system("mkdir transfer");
chdir("transfer");
//system("cd test/");
//system("pwd");
filetransferPointer = fopen(argv[6] , "ab");
if (filetransferPointer == NULL)
{
printf("\033[0;31m");
printf("[-]Error can t create file for transfer \n");
printf("\033[0m");
exit(-1);
}
/**********************************************/
char size[10];
long double size_file =0;
read(*sockfd, size, sizeof(size));
//convert data to long double
sscanf(size, "%Lf", &size_file);
printf("[i]Size of the file %Lf Kb \n",size_file);
/*************************************************/
/* Receive data in chunks of 256 bytes */
long double sz=0;
long double * ptr_sz =&sz;
while((bytesReceived = read(*sockfd, msg, 1024)) > 0)
{
//sz++;
//gotoxy(0,4);
//printf(" \r Received: %LF Mb \t \t \t",(sz/1024)); //LF for long double
//fflush(stdout);
// recvBuff[n] = 0;
/******************************************************/
double percent_done;
//long double batch_size =1/1024 ;//Mb
percent_done += 100/ size_file ; //;(batch_size/size_file)*100
//printf(" the file size is %Lf the percent_done = %lf and in in = %d \n",size_file,percent_done,(int)percent_done);
update_bar(percent_done);
fflush(stdout);
fwrite(msg, 1,bytesReceived,filetransferPointer);
usleep(20000);//sleep for 20ms
//printf("%s \n", recvBuff);
}
printf("\n");
if(bytesReceived < 0)
{
printf("[-]Error can t create file %s to recive it \n",argv[6]);
}
fclose(filetransferPointer);
printf("[i] file transmission %s is done you can check transfer folder \n",argv[6]);
}
}
void create_scoket(int * sockfd)
{
*sockfd = socket(AF_INET, SOCK_STREAM, 0);// AF_INET :IPV4 , SOCK_STREAM:TCP
if (sockfd < 0)
{
printf("\033[0;31m");
perror("[-]socket creation failed...\n");
printf("\033[0;31m");
exit(1);
}
else
{ printf("\033[0;32m");
printf("[+]Socket successfully created..\n");
printf("\033[0m");
}
}
void socket_connect(struct sockaddr_in *servaddr ,int * sockfd)
{
if (connect(*sockfd, (SA*)servaddr, sizeof(*servaddr)) <0)
{
printf("\033[0;31m");
perror("[-]connection with the server failed...\n");
printf("\033[0m");
exit(1);
}
else
{
printf("\033[0;32m");
printf("[+]connected to the server..\n");
printf("\033[0m");
}
}
int main(int argc, char **argv)
{
int sockfd, connfd;
int *ptr_sockfd;
struct sockaddr_in servaddr, client_addr;
struct sockaddr_in *ptr_servaddr;
//check argument
check_arg_client(argc,argv);
// socket create and verification
ptr_sockfd= &sockfd;
create_scoket(ptr_sockfd);
//initialize to zeo
// bzero :Set N bytes of pointer to 0.
bzero(&servaddr, sizeof(servaddr));//or you can use memset (&servaddr,'\0', sizeof(servaddr))
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(argv[2]);// the adress of the serveur
servaddr.sin_port = htons(atoi(argv[4])); //htons :Functions to convert between host and network byte order
// connect the client socket to server socket
ptr_servaddr = &servaddr ;
socket_connect(ptr_servaddr ,ptr_sockfd);
// run the lisst or transfer option
if( argc > 5)
{
share_msg(ptr_sockfd,argv, argc);
}
// close the socket
close(sockfd);
}
enter code here
I have a raspberry pi that connects to a TCP server and sends some data every couple of seconds, I want to be able to handle all kind of failures and disconnects, so at the moment I am trying a test where I disconnect the Huawei USB dongle that I am connecting through.
I have a thread that runs in the background and check the connection periodically. The code does not reconnect when I remove the USB dongle and plug it back in sometime later, I need help on how to make this more robust. At the moment on the server side I see that after I plug back in the USB dongle I see the client connect but immediately disconnect from it.
The thread is called KeepSocketOpen and inside here I call a ping function to 8.8.8.8 to see if the connection is still active and here is my code, I'm kind of new to socket programming so excuse the mess:
int ping(char *ipaddr)
{
char *command = NULL;
FILE *fp;
int x, match=0;
char* result = NULL;
size_t len = 0;
asprintf (&command, "%s %s -p 50 -r 3", "fping", ipaddr);
//printf ("%s %s -q 2>&1", "fping", ipaddr);
fp = popen(command, "r");
if (fp == NULL) {
fprintf(stderr, "Failed to execute fping command\n");
free(command);
return -1;
}
while(getline(&result, &len, fp) != -1) {
fputs(result, stdout);
//printf("%s",result);
}
for(x=0;x<len;x++)
{
if(x>5 && result[x]=='e'&& result[x-1]=='v'&& result[x-2]=='i'&& result[x-3]=='l'&& result[x-4]=='a')
{
match=1;
break;
}
}
if(match==0)
sleep(5);
free(result);
fflush(fp);
if (pclose(fp) != 0) {
perror("Cannot close stream.\n");
}
free(command);
//printf("%s\r\n",result);
if(match==0)
return -1;
else
return 1;
}
void* KeepSocketOpen(void *arg)
{
pthread_t id= pthread_self();
char tcprxbuff[1024];
int numbytes, status=0,attempts,reuse=1;
struct timeval timeout={0};
timeout.tv_sec=10;
timeout.tv_usec=0;
printf("in sock thread\r\n");
while(1)
{
if(is_socket_connected==0)
{
sock=socket(AF_INET,SOCK_STREAM,0);
addr.sin_family = AF_INET;
addr.sin_port = htons(34879);
addr.sin_addr.s_addr=inet_addr("X.X.X.X");
attempts=0;
setsockopt(sock,SOL_SOCKET,SO_SNDTIMEO,(char *)&timeout,sizeof(timeout));
setsockopt(sock,SOL_SOCKET,SO_RCVTIMEO,(char *)&timeout,sizeof(timeout));
setsockopt(sock, SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse));
status=connect(sock, (struct sockaddr *) &addr,sizeof (addr));
// wait for 5s and see if the socket has connected
do
{
delay(5);
}
while(errno && attempts++<1000);
if (attempts >=1000 || errno) // this is the fail case
{
printf("socket not connected %s\r\n",strerror(errno));
is_socket_connected=0;
close(sock);
//shutdown(sock,SHUT_RDWR);
sleep(30);
}
else
{
// fcntl(sock, F_SETFL, O_NONBLOCK);
printf("socket reconnected %d,%s\r\n",attempts,strerror(errno));
is_socket_connected=1;
write(sock, "HI FROM RASPI", strlen("HI FROM RASPI"));
}
}
else
{
numbytes=read(sock,tcprxbuff,sizeof(tcprxbuff));
if(numbytes==0)// if this is zero, socket was closed by server
{
is_socket_connected=0;
while(close(sock)==-1);
}
else
{
printf("socket connected:%d\r\n",numbytes);
status = ping("8.8.8.8");
if (status!=-1) {
printf("socket still connected:%d\r\n",status);
is_socket_connected=1;
} else {
printf("socket disconnected:%d\r\n",status);
is_socket_connected=0;
//shutdown(sock,SHUT_RDWR);
while(close(sock)==-1);
}
}
sleep(30);
}
}
}
I want to connect mqtt subscriber c client to cloudamqp but don't know how to authenticate with C program? Are there any other C language clients with working example. I am using linux.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"
#define ADDRESS "tcp://buck.rmq.cloudamqp.com:1883"
#define CLIENTID "ExampleClientSub"
#define PAYLOAD "Hello World!"
#define QOS 1
#define TIMEOUT 10000L
#define USERNAME "sakhdjs"
#define PASSWORD "B7JnaMNF2evJmWpT_WZn"
char TOPIC[12];
volatile MQTTClient_deliveryToken deliveredtoken;
void delivered(void *context, MQTTClient_deliveryToken dt)
{
printf("Message with token value %d delivery confirmed\n", dt);
deliveredtoken = dt;
}
int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
int i;
char* payloadptr;
printf("Message arrived\n");
printf(" topic: %s\n", topicName);
printf(" message: ");
payloadptr = message->payload;
for(i=0; i<message->payloadlen; i++)
{
putchar(*payloadptr++);
}
putchar('\n');
MQTTClient_freeMessage(&message);
MQTTClient_free(topicName);
return 1;
}
void connlost(void *context, char *cause)
{
printf("\nConnection lost\n");
printf(" cause: %s\n", cause);
}
int main(int argc, char* argv[])
{
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
int rc;
int ch;
printf("Enter toic name to subscribe ");
scanf("%s", TOPIC);
//printf("Enter host adderss with format like tcp://localhost:1883 ");
// scanf("%s", ADDRESS);
MQTTClient_create(&client, ADDRESS, CLIENTID,
MQTTCLIENT_PERSISTENCE_NONE,NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);
if ((rc = MQTTClient_connect(client, &conn_opts ,USERNAME,PASSWORD)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to connect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
"Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS);
MQTTClient_subscribe(client, TOPIC, QOS);
do
{
ch = getchar();
} while(ch!='Q' && ch != 'q');
MQTTClient_unsubscribe(client, TOPIC);
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);
return rc;
}
How to connect using paho mqtt subscriber and also publish? Are there any other C language clients for this purpose? Or any other way in C language with code?
You set the username and password fields in the MQTTClient_connectOptions structure before you pass it to the MQTTClient_connect() function.
MQTTClient_create(&client, ADDRESS, CLIENTID,
MQTTCLIENT_PERSISTENCE_NONE,NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
conn_opts.username = USERNAME
conn_opts.password = PASSWORD
I have a little problem about paho mqtt library.
I register a callback function MQTTClient_messageArrived and MQTTClient_connectionLost.
And I call MQTTClient_subscribe() or MQTTClient_unsubscribe() in this callback function. After running this callback function. I got a error code (-3) from MQTTClient_connectionLost. Furthermore, I print the cause is NULL.
Is any possible problem to my problem? Thanks
Here are my initialize function and callback function:
void mqtt_initialize(void){
int rc;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
if(MQTTClient_create(&g_MQTT_client, BROKER_ADDR, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL) < 0){
g_mqtt_exist = MQTT_INSTANCE_NOT_EXIST;
} else {
g_mqtt_exist = MQTT_INSTANCE_EXIST;
}
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
MQTTClient_setCallbacks(g_MQTT_client, NULL, mqtt_connlost_cb, mqtt_arrived_cb, mqtt_delivered_cb);
if ((rc = MQTTClient_connect(g_MQTT_client, &conn_opts)) != MQTTCLIENT_SUCCESS) {
MAIN_PRINT_DEBUG(0, "Failed to connect MQTT broker, return code %d\n", rc);
mqtt_free();
}
/* set subscribe control topic */
MQTTClient_subscribe(g_MQTT_client, "topic_1", MQTT_QOS);
}
int mqtt_arrived_cb(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
int ret = 0;
printf("topic: %s\n", topicName);
if(!strcmp(topicName, "topic_1")){
printf("topic_1\n");
ret = MQTTClient_subscribe(g_MQTT_client, "topic_2", 0);
if (ret < 0){
printf("mqtt operation fail\n");
}
}
return 1;
}
void mqtt_connlost_cb(void *context, char *cause)
{
MAIN_PRINT_DEBUG(0, "\n MQTT Connection lost\n");
MAIN_PRINT_DEBUG(0," cause: %s\n", cause);
}
Did you try connecting any other client to same broker with same client id? That could be a possible case if you are getting connection lost. Also if your callback throws exception, it will cause connection lost, however in this case paho will reconnect.