#include <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <signal.h>


#define SIZE sizeof(struct sockaddr_in)

void timeout(int nsig);

int ret,rt;
int allbytes;
time_t t,lastt;

int main(){
    int sockfd;
    int ret;
    char c,rc,i;
    char *ptxt="Hello from client !!!";
    char pbuf[1024];
    char pbuffer[1024];
    char e=(int)255;

    struct sockaddr_in server = {AF_INET,7010};

    printf("%s","Enter IP server address :");
    if(fgets(pbuffer,sizeof(pbuffer),stdin)){
	 server.sin_addr.s_addr = inet_addr(pbuffer);
//	 server.sin_port = pbuffer;	 
    } else {
        printf("%s  %s\n","Cannot connect with ",pbuffer);
	exit(1);
    };

    printf("%s","Enter server port :");
    if(fgets(pbuffer,sizeof(pbuffer),stdin)){
	 server.sin_port = htons(atoi(pbuffer));	 
    } else {
        printf("%s  %s\n","Cannot connect with ",pbuffer);
	exit(1);
    };
    
    if(( sockfd= socket(AF_INET, SOCK_STREAM,0))==-1) exit(1);
    if( connect(sockfd, (struct sockaddr *) &server, SIZE)==-1) exit(1);

    printf("%s\n","--- CLIENT HERE---");
    printf("%s\n","Type Ctrl-C for exit");    
    memset(pbuffer,'0',1023);
    pbuffer[1024]=0x0;

    i=0;
    signal(SIGALRM,timeout);
    alarm(2);

    for(i=0;i<1024;i++){
        ret = send(sockfd,pbuffer,strlen(pbuffer),0);    
	//printf("%d Send %d bytes to server \n",i,strlen(pbuffer));
	allbytes+=ret;
    };

//    printf("Always sent %d bytes to server \n",i*strlen(pbuffer));
    close(sockfd);
    exit(0);
}

void timeout(int nsig){
    printf("We sent %d bytes. Speed=%d B/s %d KB/s\n",allbytes,allbytes/(time(NULL)-lastt),(allbytes/(time(NULL)-lastt))/1024);		    
    lastt = time(NULL);
    signal(SIGALRM,timeout);
    alarm(2);
    allbytes=0;
};
