winsock select服务端模型

来源:互联网 发布:mysql free result 编辑:程序博客网 时间:2024/04/27 21:52
#include "stdafx.h"
#include <windows.h>
#include <Winsock2.h>
#pragma comment(lib,"Ws2_32.lib")
void InitSocket()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
  
wVersionRequested = MAKEWORD( 2, 2 );
  
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
  /* Tell the user that we could not find a usable */
  /* WinSock DLL.                                  */
  return;
}
  
/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater    */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we      */
/* requested.                                        */
  
if ( LOBYTE( wsaData.wVersion ) != 2 ||
   HIBYTE( wsaData.wVersion ) != 2 ) {
  /* Tell the user that we could not find a usable */
  /* WinSock DLL.                                  */
  WSACleanup( );
  return;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
InitSocket();
SOCKET sock=::socket(AF_INET,SOCK_STREAM,0);
if(sock==INVALID_SOCKET)
{
  printf("创建socket失败");
  WSACleanup( );
  return 0;
}
::sockaddr_in serAddr;
serAddr.sin_family=AF_INET;
serAddr.sin_port=::htons(3456);
serAddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
if(SOCKET_ERROR==bind(sock,(sockaddr*)&serAddr,sizeof(sockaddr)))
{
  printf("绑定失败");
  WSACleanup( );
  return 0;
}
listen(sock,5);
fd_set fdSocket;
FD_ZERO(&fdSocket);
FD_SET(sock,&fdSocket);
while(true)
{
  fd_set fdRead=fdSocket;
  int nRet=::select(0,&fdRead,NULL,NULL,NULL);
  if(nRet>0)
  {
   for(int i=0;i<(int)fdSocket.fd_count;i++)
   {
    if(FD_ISSET(fdSocket.fd_array[i],&fdRead))
    {
     //有新的连接到达
     if(fdSocket.fd_array[i]==sock)
     {
      if(fdSocket.fd_count<FD_SETSIZE)
      {
       ::sockaddr_in addr;
       int len=sizeof(sockaddr);
       SOCKET client=accept(sock,(sockaddr*)&addr,&len);
       printf("接收到新的连接 : %s&#92;n",::inet_ntoa(addr.sin_addr));
       FD_SET(client,&fdSocket);
      }
      else
      {
       printf("too many connections&#92;n");
      }
     }
     else
     {
      char*buf=new char[1024];
      int nRecv=::recv(fdSocket.fd_array[i],buf,1024,0);
      if(nRecv>0)
      {
       buf[nRecv]='&#92;0';
       printf("收到数据: %s&#92;n",buf);
      }
      else
      {
       ::closesocket(fdSocket.fd_array[i]);
       FD_CLR(fdSocket.fd_array[i],&fdSocket);
       printf("一客户端断开连接&#92;n");
      }
      delete []buf;
     }
    }
   }
  }
}
return 0;
}