#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#define BUF_SIZE 1024
void error_handling(char* message);
int main(int argc, char* argv[])
{
WSADATA wsadata;
SOCKET hServSock, hClntSock;
SOCKADDR_IN servAddr, clntAddr;
TIMEVAL timeout;
fd_set reads, cp_reads;
int adr_sz;
int str_len, i,fd_num;
char buf[BUF_SIZE];
if (argc != )
{
printf("usage:%s <port>\n",argv[]);
exit();
}
if (WSAStartup(MAKEWORD(, ), &wsadata) != )
error_handling("WSAStartup error");
hServSock = socket(PF_INET, SOCK_STREAM, );
memset(&servAddr, , sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(atoi(argv[]));
if (bind(hServSock, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR)
error_handling("bind error");
if (listen(hServSock, ) == SOCKET_ERROR)
error_handling("listen error");
FD_ZERO(&reads);
FD_SET(hServSock, &reads);
while ()
{
cp_reads = reads;
timeout.tv_sec = ;
if ((fd_num = select(, &cp_reads, , , &timeout)) == SOCKET_ERROR)
break;
if (fd_num == )
continue;
for (i = ;i < reads.fd_count;i++)
{
if (FD_ISSET(reads.fd_array[i], &cp_reads))
{
if (reads.fd_array[i] == hServSock)
{
adr_sz = sizeof(clntAddr);
hClntSock = accept(hServSock, (SOCKADDR*)&servAddr, &adr_sz);
FD_SET(hClntSock, &reads);
printf("connected client:%d\n", hClntSock);
}
else
{
str_len = recv(reads.fd_array[i], buf, BUF_SIZE - , );
if (str_len == )
{
FD_CLR(reads.fd_array[i], &reads);
closesocket(cp_reads.fd_array[i]);
printf("closed client:%d\n", cp_reads.fd_array[i]);
}
else
send(reads.fd_array[i], buf, str_len, );
}
}
}
}
closesocket(hServSock);
WSACleanup();
return ;
}
void error_handling(char* message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit();
}