超简单的一个重叠io模型,重在学习理解
#include "stdio.h"
#include "winsock2.h"
#pragma comment(lib,"ws2_32.lib")
int main(void)
{
WSADATA wsa;
WSAStartup(MAKEWORD(2,2),&wsa);
SOCKET ListenSocket,AcceptSocket;
WSAOVERLAPPED overlapped;
WSAEVENT wsaevent;
WSABUF buf;
char buffer[50];
memset(b,0,sizeof(b));
memset(buffer,0,sizeof(buffer));
unsigned long recvtotal=0;
unsigned long flags=0;
buf.buf=buffer;
buf.len=sizeof(buffer)-1;
ListenSocket=WSASocket(AF_INET,SOCK_STREAM,IPPROTO_TCP,NULL,NULL,WSA_FLAG_OVERLAPPED);
if(ListenSocket==SOCKET_ERROR)
{
printf("create socket failed /n");
return 0;
}
SOCKADDR_IN sAddr,cAddr;
sAddr.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
sAddr.sin_family=AF_INET;
sAddr.sin_port=htons(5124);
if(bind(ListenSocket,(sockaddr *)&sAddr,sizeof(sockaddr))==SOCKET_ERROR)
{
printf("bind error /n");
return 0;
}
listen(ListenSocket,1);
int len=sizeof(sockaddr);
AcceptSocket=accept(ListenSocket,(sockaddr *)&cAddr,&len);
if(AcceptSocket==INVALID_SOCKET)
{
printf("accept failed ! /n");
}
int ret=0;
wsaevent=WSACreateEvent();
while(true){
memset(buffer,0,sizeof(buffer));
overlapped.hEvent=wsaevent;
if((ret=WSARecv(AcceptSocket,&buf,1,&recvtotal,&flags,&overlapped,NULL))==SOCKET_ERROR)
{
printf("%d /n",WSAGetLastError());
if(WSAGetLastError()!=WSA_IO_PENDING)
{
printf("WSARecv failed with error %d/n",WSAGetLastError());
closesocket(AcceptSocket);
return 0;
}
}
int index;
DWORD recved;
index=WSAWaitForMultipleEvents(1,&wsaevent,FALSE,WSA_INFINITE,FALSE);
if(index!=WSA_WAIT_FAILED)
{
WSAResetEvent(wsaevent);
}
WSAGetOverlappedResult(AcceptSocket,&overlapped,&recved,FALSE,&flags);
if(recved==0 )
{
printf("client socket have closed /n");
closesocket(AcceptSocket);
return 0;
}
else
{
printf("%s /n",buffer);
}
}
closesocket(AcceptSocket);
WSACleanup();
return 0;
}
很简单所以就没写注释了。