I currently have a sensor located remotely connected using TCP. Problem is that the remote location keeps disconnecting, a scenario which i dont know how to rectify on my code. I have 3/10 idea of what im doing and most of the lines on this code is from internet.
Question is, how do i implement a code that automatically reconnects to my tcp client? tried a lot of methods but doesnt seem to work. The code however works perfectly provided connection is seamless.
#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <time.h>
#define MAX 1000
#define PORT 14344
#define SA struct sockaddr
int main()
{
time_t t;
time(&t);
int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;
unsigned char buff[MAX];
int n,dd,a,b,c;
char timebuffer [80];
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
strftime (timebuffer,80,"/home/%m%d%y_%H%M%S",timeinfo);
FILE *fil1;
fil1=fopen(timebuffer,"wb");
printf("%s",ctime(&t));
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0); }
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
printf("socket bind failed...\n");
exit(0); }
else
{
printf("Socket successfully binded..\n");
if ((listen(sockfd, 5)) != 0) {
printf("Listen failed...\n");
exit(0); }
else
printf("Server listening..\n");
len = sizeof(cli);
connfd = accept(sockfd, (SA*)&cli, &len);
if (connfd < 0) {
printf("server accept failed...\n");
exit(0); }
else
printf("server accepted...\n");
while (1){
bzero(buff, MAX);
dd=read(connfd, buff, sizeof(buff));
printf("\n");
for(a=0; a<=dd-1; a++){fprintf(fil1, "%c", buff[a]);printf("%02X", buff[a]);}
printf("\n");
bzero(buff, MAX);
}
}
close(connfd);
}
You must send some data. If you do not send data, there is no guarantee that you can detect a lost connection. The only way you can reliably tell if the other end is still connected is if you try to send some data to it and it fails. Without trying, you have no way to know if the other end is there.
Next, you must check read
's return value. If there's an error, you need to close connfd
and loop back to the accept
call to get a new connection.