WSAEventSelect模型 ---應用實例,重寫TCP服務器實例

// WSAEvent.cpp : 定義控制檯應用程序的入口點。 //  #include "stdafx.h" #include <winsock2.h> #include <stdio.h>
  
#pragma comment(lib,"WS2_32")
class CInitSock { public: CInitSock(BYTE minorVer=2,BYTE majorVer=2) { WSADATA wsaData; WORD sockVersion = MAKEWORD(minorVer,majorVer); if(::WSAStartup(sockVersion,&wsaData)!=0) { exit(0); } } ~CInitSock() { ::WSACleanup(); } }; CInitSock initSock; int _tmain(int argc, _TCHAR* argv[]) { //事件句柄和套接字句柄表
 WSAEVENT eventArray[WSA_MAXIMUM_WAIT_EVENTS]; SOCKET sockArray[WSA_MAXIMUM_WAIT_EVENTS]; int nEventTotal = 0; USHORT nPort = 4567; SOCKET sListen = ::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = htons(nPort); sin.sin_addr.S_un.S_addr = INADDR_ANY; if(::bind(sListen,(sockaddr*)&sin,sizeof(sin))==SOCKET_ERROR) { printf("Failed bind()\n"); return -1; } ::listen(sListen,5); //建立事件對象,並關聯到新的套接字
    WSAEVENT event = ::WSACreateEvent(); ::WSAEventSelect(sListen,event,FD_ACCEPT|FD_CLOSE); //添加到表中
    eventArray[nEventTotal] = event; sockArray[nEventTotal] = sListen; nEventTotal++; //處理網絡事件
    while(TRUE) { //在全部事件上等待
        int nIndex = ::WSAWaitForMultipleEvents(nEventTotal,eventArray,FALSE,WSA_INFINITE,FALSE); //對每一個事件調用函數,肯定它的狀態
        nIndex = nIndex-WSA_WAIT_EVENT_0; for(int i=nIndex;i<nEventTotal;i++) { nIndex = ::WSAWaitForMultipleEvents(1,&eventArray[i],TRUE,1000,FALSE); if(nIndex == WSA_WAIT_FAILED || nIndex == WSA_WAIT_TIMEOUT) { continue; } else { //獲取到來的通知消息,自動重置受信事件
                WSANETWORKEVENTS event; ::WSAEnumNetworkEvents(sockArray[i],eventArray[i],&event); if(event.lNetworkEvents & FD_ACCEPT) { if(event.iErrorCode[FD_ACCEPT_BIT] == 0) { if(nEventTotal>WSA_MAXIMUM_WAIT_EVENTS) { printf("Too many connections!"); continue; } SOCKET sNew = ::accept(sockArray[i],NULL,NULL); WSAEVENT event = ::WSACreateEvent(); ::WSAEventSelect(sNew,event,FD_READ|FD_CLOSE|FD_WRITE); //添加到表中
                        eventArray[nEventTotal] = event; sockArray[nEventTotal] = sNew; nEventTotal++; } } else if(event.lNetworkEvents & FD_READ) { if(event.iErrorCode[FD_ACCEPT_BIT] == 0) { char szText[256]; int nRecv = ::recv(sockArray[i],szText,strlen(szText),0); if(nRecv > 0) { szText[nRecv] = '\0'; printf("接收到數據:%s\n",szText); } } } else if(event.lNetworkEvents & FD_CLOSE) { if(event.iErrorCode[FD_ACCEPT_BIT] == 0) { ::closesocket(sockArray[i]); for(int j=i;j<nEventTotal-1;j++) { eventArray[j] = eventArray[j+1]; sockArray[j] = sockArray[j+1]; } nEventTotal--; } } else if(event.lNetworkEvents & FD_WRITE) { } } } } return 0; }
相關文章
相關標籤/搜索