#include #include #include #include #include #include #include #include #include #define BUF_WORDS 65536 uint32_t buf[BUF_WORDS]; char rdbuf[4096]; int main(int argc, char **argv) { int sockfd, newsockfd, portno, clilen, n, ret; struct sockaddr_in serv_addr, cli_addr; int i; fd_set read_fds, write_fds; if (argc != 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return -1; } sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("socket"); return -2; } bzero((char *) &serv_addr, sizeof(serv_addr)); portno = atoi(argv[1]); if (portno == 0 || portno > 65536) { fprintf(stderr, "Invalid port\n"); return -6; } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(portno); serv_addr.sin_addr.s_addr = INADDR_ANY; if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { perror("bind"); return -3; } if (listen(sockfd, 1) < 0) { perror("listen"); return -4; } for (;;) { printf("listening on port %d\n", portno); clilen = sizeof(cli_addr); newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); if (newsockfd < 0) { perror("accept"); return -5; } printf("got new client\n"); memset(buf, 0xff, sizeof(buf)); i = 0; do { FD_ZERO(&read_fds); FD_ZERO(&write_fds); FD_SET(newsockfd, &read_fds); FD_SET(newsockfd, &write_fds); ret = select(newsockfd+1, &read_fds, &write_fds, NULL, NULL); if (ret == 1) { if (FD_ISSET(newsockfd, &read_fds)) { ret = recv(newsockfd, rdbuf, sizeof(rdbuf), 0); printf("read %d\n", ret); } if (FD_ISSET(newsockfd, &write_fds)) { ret = send(newsockfd, buf, sizeof(buf), 0); // printf("wrote %d\n", ret); } } buf[i++] -= 1; i %= BUF_WORDS; } while(ret > 0); shutdown(newsockfd, SHUT_RD|SHUT_WR); close(newsockfd); } close(sockfd); return 0; }