#include<winsock2.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<process.h>
#define Num 10
SOCKET accSock;
char buf[128];
unsigned int _stdcall ThreadFun(PVOID Pm)
{
while(1)
{
recv(accSock,buf,sizeof(buf),0);
printf("[C] %s\n",buf);
if(strcmp(buf,"quit")==0) break;
//sprintf(buf,"echo %d:",++count);
gets(buf);//
send(accSock,buf,sizeof(buf),0);
}
return 0;
}
int main()
{
WSADATA wsaData;
PHOSTENT hostinfo;
SOCKADDR_IN addr,addrout;
SOCKET server;
HANDLE handle[Num];
int port,len=sizeof(SOCKADDR_IN),count=0;
char *ip;
if(WSAStartup(0x202,&wsaData)!=0)
{
printf("initiate Winsock Dll error\n");
return -1;
}
server =socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
addr.sin_family =AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port =htons(6666);
bind(server,(SOCKADDR*)&addr,sizeof(addr));
gethostname(buf,sizeof(buf));
hostinfo =gethostbyname(buf);
ip =inet_ntoa(* (IN_ADDR* )*hostinfo->h_addr_list);
listen(server,2);
printf("server %s waiting for conection...\n",ip);
accSock =accept(server,(SOCKADDR*)&addrout,&len);
ip =inet_ntoa(addrout.sin_addr);
port =htons(addrout.sin_port);
printf("[S] accept client %s : %d\n",ip,port);
//printf("[I] message:");//
for(int i=0;i<Num;i++)
handle[i]=(HANDLE)_beginthreadex(NULL,0,ThreadFun,NULL,0,NULL);
WaitForMultipleObjects(Num,handle,TRUE,INFINITE);
closesocket(accSock);
closesocket(server);
WSACleanup();
return 0;
}