#include #include #include #include #include #include #include #include int init_socket(int* fd, struct sockaddr_in* sa, const char* host, const int port){ struct hostent *he; *fd = socket(PF_INET, SOCK_STREAM, 0); if(*fd < 0){ perror("socket"); return -1; } he = (struct hostent*)gethostbyname(host); if (he == NULL){ herror(host); return -1; } bzero(sa, sizeof(struct sockaddr_in)); sa->sin_family = AF_INET; sa->sin_port = htons (port); bcopy(he->h_addr_list[0], &sa->sin_addr, he->h_length); return 1; } int main(void){ struct sockaddr_in sa; int fd, ret, count = 3;; const int bufSize = 1024; char buf[bufSize]; const char host[] = "127.0.0.1"; fd_set fdset; struct timeval tval; init_socket(&fd, &sa, host, 8080); if(fd < 0) { perror("socket"); return 1; } ret = connect(fd, (struct sockaddr *)&sa, sizeof sa); printf("[CONNECT] ret: %d, err: %d\n", ret, errno); if( ret != 0 ){ perror("connect fail"); return 2; } for(;;){ signal(SIGPIPE, SIG_IGN); write(fd, "ha\n", 3); if(count-- <0){ write(fd, "\n", sizeof "\n"); printf("sent close message\n"); } FD_ZERO(&fdset); FD_SET(fd, &fdset); tval.tv_sec = 0; tval.tv_usec = 103; ret = select(fd + 1, &fdset, NULL, NULL, &tval); printf("[SELECT] ret: %d, err: %d\n", ret, errno); ret = recv(fd, buf, bufSize, MSG_PEEK); printf("[RECV] ret: %d, err: %d\n", ret, errno); sleep(1); signal(SIGPIPE, SIG_DFL); if (errno == EPIPE){ break; } } close(fd); return 0; }