netsocket with select module [first]

netsocket with select module [first]

//不完善的select模型 雏形

#include <windows.h>
#include <stdio.h>
#define PORT 9318
#pragma comment(lib,"ws2_32")
//服务器
FD_SET   WriteSet;     
FD_SET   ReadSet;          

DWORD WINAPI work(void * data)
{
 SOCKET client=(SOCKET)data;
 while(1){
  char recvBuf[100];
  recv(client,recvBuf,100,0);
  if   (GetLastError()   !=   WSAEWOULDBLOCK)     
  {     
   printf("conn err   %d/n",WSAGetLastError());     
   closesocket(client);     
   printf("Closing   socket   number   %d/n",   client);
   break;
  }
  printf("%s/n",recvBuf);
  send(client,recvBuf,strlen(recvBuf)+1,0);
 }
 closesocket(client);
 return 0;
}

int main(){
 //加载并初始化winsock ddl
 
 WORD wVersionRequested;
 WSADATA wsaData;
 wVersionRequested = MAKEWORD(2,2);
 ::WSAStartup(wVersionRequested,&wsaData);
 SOCKET server=socket(AF_INET,SOCK_STREAM,0);
 
 SOCKADDR_IN addrSrv;
 addrSrv.sin_addr.S_un.S_addr=inet_addr("0.0.0.0");;
 addrSrv.sin_family=AF_INET;
 addrSrv.sin_port=htons(PORT);
 
 bind(server,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
 
 listen(server,5);
 
 SOCKADDR_IN addrClient;
 int len=sizeof(SOCKADDR_IN);
 for(;;)
 {
  FD_ZERO(&ReadSet);     
  FD_SET(server, &ReadSet); //定位连接
  SOCKET client = select(server+1,&ReadSet,NULL,NULL,NULL);
  client=accept(server,(SOCKADDR*)&addrClient,&len);
  printf("%s/n",inet_ntoa(addrClient.sin_addr));
  FD_ZERO(&WriteSet);    //为0 
  FD_SET(server, &WriteSet); //定位接收
  HANDLE t=CreateThread(0,0,work,(void*)client,0,0);
 }
 closesocket(server);
 ::WSACleanup();
 return 0;
}

 

你可能感兴趣的:(server,Stream,socket,Module,null,winapi)