1 #include2 #include 3 #include 4 #include 5 6 #define BUF_SIZE 1024 7 void error_handling(char* message); 8 9 int main(int argc, char* argv[])10 {11 WSADATA wsadata;12 SOCKET hServSock, hClntSock;13 SOCKADDR_IN servAddr, clntAddr;14 TIMEVAL timeout;15 fd_set reads, cp_reads;16 17 int adr_sz;18 int str_len, i,fd_num;19 char buf[BUF_SIZE];20 21 if (argc != 2)22 {23 printf("usage:%s \n",argv[0]);24 exit(1);25 }26 if (WSAStartup(MAKEWORD(2, 2), &wsadata) != 0)27 error_handling("WSAStartup error");28 29 hServSock = socket(PF_INET, SOCK_STREAM, 0);30 memset(&servAddr, 0, sizeof(servAddr));31 servAddr.sin_family = AF_INET;32 servAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);33 servAddr.sin_port = htons(atoi(argv[1]));34 35 if (bind(hServSock, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR)36 error_handling("bind error");37 if (listen(hServSock, 5) == SOCKET_ERROR)38 error_handling("listen error");39 40 FD_ZERO(&reads);41 FD_SET(hServSock, &reads);42 43 while (1)44 {45 cp_reads = reads;46 timeout.tv_sec = 5;47 48 if ((fd_num = select(0, &cp_reads, 0, 0, &timeout)) == SOCKET_ERROR)49 break;50 if (fd_num == 0)51 continue;52 53 for (i = 0;i < reads.fd_count;i++)54 {55 if (FD_ISSET(reads.fd_array[i], &cp_reads))56 {57 if (reads.fd_array[i] == hServSock)58 {59 adr_sz = sizeof(clntAddr);60 hClntSock = accept(hServSock, (SOCKADDR*)&servAddr, &adr_sz);61 FD_SET(hClntSock, &reads);62 printf("connected client:%d\n", hClntSock);63 }64 else65 {66 str_len = recv(reads.fd_array[i], buf, BUF_SIZE - 1, 0);67 if (str_len == 0)68 {69 FD_CLR(reads.fd_array[i], &reads);70 closesocket(cp_reads.fd_array[i]);71 printf("closed client:%d\n", cp_reads.fd_array[i]);72 }73 else74 send(reads.fd_array[i], buf, str_len, 0);75 }76 }77 }78 }79 closesocket(hServSock);80 WSACleanup();81 return 0;82 }83 84 void error_handling(char* message)85 {86 fputs(message, stderr);87 fputc('\n', stderr);88 exit(1);89 }