1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> #include <WinSock2.h>
#define BUF_SIZE 1024
void ErrorHandling(char *message);
int main(int argc, char* argv[]) { WSADATA wsaData; SOCKET hServSock, hClntSock; SOCKADDR_IN servAdr, clntAdr; TIMEVAL timeout; fd_set reads, cpyReads;
int adrSz; int strLen, fdNum; unsigned int i; char buf[BUF_SIZE];
if (argc != 2) { printf("Usage : %s <port>\n", argv[0]); exit(1); }
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) ErrorHandling("WSAStartup() error");
hServSock = socket(PF_INET, SOCK_STREAM, 0); memset(&servAdr, 0, sizeof(servAdr)); servAdr.sin_family = AF_INET; servAdr.sin_addr.s_addr = htonl(INADDR_ANY); servAdr.sin_port = htons(atoi(argv[1]));
if (bind(hServSock, (SOCKADDR*)&servAdr, sizeof(servAdr)) == SOCKET_ERROR) ErrorHandling("bind() error"); if (listen(hServSock, 5) == SOCKET_ERROR) ErrorHandling("listen() error");
FD_ZERO(&reads); FD_SET(hServSock, &reads);
while (1) { cpyReads = reads; timeout.tv_sec = 5; timeout.tv_usec = 5000; if ((fdNum = select(0, &cpyReads, 0, 0, &timeout)) == SOCKET_ERROR) break; if (fdNum == 0) continue; for (i=0; i<reads.fd_count; i++) { if (FD_ISSET(reads.fd_array[i], &cpyReads)) { if (reads.fd_array[i] == hServSock) { adrSz = sizeof(clntAdr); hClntSock = accept(hServSock,(SOCKADDR*)&clntAdr,&adrSz); FD_SET(hClntSock,&reads); printf("connected client: %d \n",hClntSock); } else { strLen = recv(reads.fd_array[i],buf,BUF_SIZE-1,0); if (strLen == 0) { FD_CLR(reads.fd_array[i],&reads); closesocket(cpyReads.fd_array[i]); printf("closed client: %d \n",cpyReads.fd_array[i]); } else { send(reads.fd_array[i],buf,strLen,0); } } } } } closesocket(hServSock); WSACleanup(); return 0; }
void ErrorHandling(char* message) { fputs(message,stderr); fputc('\n',stderr); exit(1); }
|