tag: Maximum number of reconnections of Socket Client tianjian
# Include <stdlib. h> # include <dirent. h> # include <time. h> # include <unistd. h> # include <dirent. h> # include <sys/types. h> # include <errno. h> # include <sys/socket. h> # include <netinet/in. h> # include <ARPA/inet. h> # include <stdio. h> # include <error. h> # include <string. h> int readnet (INT sockid, register char * PTR, short nbytes) {int nleft = 0, nread = 0; fd_set readyfd; struct timeval timeout; int ret; nleft = nbytes; fd_zero (& readyfd); fd_set (sockid, & readyfd); timeout. TV _sec = 0; timeout. TV _usec = 500000; // 0.5 seconds ret = select (sockid + 1, null, & readyfd, null, & timeout); If (Ret <= 0) {return-1 ;} nleft = nbytes; while (nleft> 0) {nread = read (sockid, PTR, nleft); If (nread <= 0) {return (nread );} nleft-= nread; PTR + = nread;} return nbytes-nleft;} int client () {char Buf [200] = {0}; int isockfd = socket (pf_inet, sock_stream, 0);/* 1. prepare socket */If (isockfd =-1) {return-1;} struct sockaddr_in ADDR; ADDR. sin_family = pf_inet; ADDR. sin_port = htons (17777); inet_aton ("127.0.0.1", & ADDR. sin_addr); // unsigned long ul = 1; // IOCTL (isockfd, fionbio, & UL); // sets the non-blocking mode struct timeval timeout; timeout. TV _sec = 10; timeout. TV _usec = 500000; // setsockopt (isockfd, sol_socket, so_rcvtimeo, (char *) & timeout, sizeof (timeout); fd_set readyfd; int ret; int inum = 0; while (-1 = connect (isockfd, (struct sockaddr *) & ADDR, sizeof (ADDR) {inum ++; printf ("-------- % d reconnection \ n", inum); sleep (1); If (inum = 10) {printf ("----------- Connection Failed \ n "); return-1 ;}} ret = select (isockfd, null, & readyfd, null, & timeout); // printf ("-------- connect = % d \ n", IRES ); printf ("-------- select = % d \ n", RET); write (isockfd, (char *) "Hello world, I'm client", 100 ); // ret = select (isockfd, null, & readyfd, null, & timeout); printf ("--------- ret = % d \ n", RET); int I; for (I = 0; I <6; I ++) {If (ret = 0) {int iret = read (isockfd, Buf, 100 ); printf ("--- 1 ---- Timeout: % d \ n", I); If (iret <= 0) {continue;} else {break ;}} if (Ret> 0) {int Iset = fd_isset (isockfd, & readyfd); int iret = read (isockfd, Buf, 100); printf ("--- 2 ---- timeout times: % d \ n ", I) ;}/// int iret = read (isockfd, Buf, 100); printf (" ------- Buf = % s \ n ", Buf ); printf ("-------------- function end -------- \ n"); Return 0;} int main () {client (); Return 0 ;}
maximum number of reconnections of Socket Client tianjian