winsock select服务端模型

#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;
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值