0

This is the client program where the intended for loop has to be set. But i am not able to understand where to include it as i am new to socket programming. Please someone help me code it. I need this code to include a loop which will help me continuously transfer random data to the server in every n seconds.

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void error(char *msg)
{
    perror(msg);
    exit(0);
}

int main(int argc, char *argv[])
{
    int sockfd, portno, n;

    struct sockaddr_in serv_addr;
    struct hostent *server;

    char buffer[256];
    if (argc < 3) {
       fprintf(stderr,"usage %s hostname port\n", argv[0]);
       exit(0);
    }
    portno = atoi(argv[2]);
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) 
        error("ERROR opening socket");
    server = gethostbyname(argv[1]);
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        exit(0);
    }
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, 
         (char *)&serv_addr.sin_addr.s_addr,
         server->h_length);
    serv_addr.sin_port = htons(portno);
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) 
        error("ERROR connecting");
    printf("Please enter the message: ");
    bzero(buffer,256);
    fgets(buffer,255,stdin);
    n = write(sockfd,buffer,strlen(buffer));
    if (n < 0) 
         error("ERROR writing to socket");
    bzero(buffer,256);
    n = read(sockfd,buffer,255);
    if (n < 0) 
         error("ERROR reading from socket");
    printf("%s\n",buffer);
    return 0;
}

1 Answers1

0

Add #include<time.h> at the beggining. Use the function given below to add delay.

void delay(unsigned short secs)
{
    unsigned milli_seconds = 1000 * secs;

    clock_t start_time = clock(); //declaration in time.h 

    while (clock() < start_time + milli_seconds)
        ;
}

Inside main() call the delay(interval) in infinite loop to send timestamp, id and

int main(int argc, char *argv[])
{
    unsigned data_id=0;
    char data[1024];
    ...
    while(1)
    {
          delay(5);
          send(client_sock,data,strlen(data),0);
    }
    ..
    return EXIT_SUCCESS;
}

I hope you get it.

Note: Do not use bzero() instead use memset(). For more read this one.

Premkumar chalmeti
  • 800
  • 1
  • 8
  • 23