Windows网络编程Overlapped Event基本使用,下面是一个简单的例子
#include <winsock2.h>
#include <windows.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
#define LISTEN_PORT 5080
#define BUFF_SIZE 256
int main(void)
{
WSADATA wsaData;
int nRet;
SOCKET listen_sock;
SOCKADDR_IN listen_addr;
SOCKET client_sock;
SOCKADDR_IN client_addr;
int client_addr_len = sizeof(client_addr);
WSAEVENT read_event;
WSAOVERLAPPED client_overlapped;
char buff[BUFF_SIZE];
WSABUF wsaBuf;
int recv_bytes = 0;
DWORD flags = 0;
DWORD index;
nRet = WSAStartup(MAKEWORD(2,2), &wsaData);
if(0 != nRet)
{
printf("WSAStartup() failed, error:%d.\n", WSAGetLastError());
return 1;
}
listen_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(INVALID_SOCKET == listen_sock)
{
printf("socket() failed, error:%d.\n", WSAGetLastError());
goto retflag1;
}
listen_addr.sin_family = AF_INET;
listen_addr.sin_addr.s_addr = htonl(INADDR_ANY);
listen_addr.sin_port = htons(LISTEN_PORT);
nRet = bind(listen_sock, (SOCKADDR*)&listen_addr, sizeof(listen_addr));
if(nRet == SOCKET_ERROR)
{
printf("bind() failed, error:%d.\n", WSAGetLastError());
closesocket(listen_sock);
goto retflag1;
}
nRet = listen(listen_sock, 5);
if(SOCKET_ERROR == nRet)
{
printf("listen() failed, error:%d.\n", WSAGetLastError());
closesocket(listen_sock);
goto retflag1;
}
client_sock = accept(listen_sock, (SOCKADDR*)&client_addr, &client_addr_len);
if(INVALID_SOCKET == client_sock)
{
printf("accept() failed, error:%d.\n", WSAGetLastError());
closesocket(listen_sock);
goto retflag1;
}
read_event = WSACreateEvent();
if(WSA_INVALID_EVENT == read_event)
{
printf("WSACreateEvent() failed, error:%d.\n", WSAGetLastError());
closesocket(listen_sock);
closesocket(client_sock);
goto retflag1;
}
while(1)
{
memset(&client_overlapped, 0, sizeof(client_overlapped));
client_overlapped.hEvent = read_event;
wsaBuf.buf = buff;
wsaBuf.len = BUFF_SIZE;
if(WSARecv(client_sock, &wsaBuf, 1, &recv_bytes, &flags, &client_overlapped, NULL) == SOCKET_ERROR)
{
if(WSAGetLastError() != WSA_IO_PENDING)
{
printf("WSARecv failed, error:%d.\n", WSAGetLastError());
}
else
{
printf("WSARecv WSA_IO_PENDING.\n");
}
}
else
{
printf("%s", wsaBuf.buf);
}
index = WSAWaitForMultipleEvents(1, &read_event, FALSE, WSA_INFINITE, FALSE);
while(!WSAResetEvent(read_event))
{
printf("WSAResetEvent failed, error:%d.\n", WSAGetLastError());
}
WSAGetOverlappedResult(client_sock, &client_overlapped, &recv_bytes, FALSE, &flags);
if(recv_bytes <= 0)
{
printf("WSAGetOverlappedResult() socket close");
closesocket(client_sock);
WSACloseEvent(read_event);
break;
}
printf("%s", wsaBuf.buf);
}
closesocket(listen_sock);
retflag1:
nRet = WSACleanup();
if(0 != nRet)
{
printf("WSACleanup() failed, error:%d.\n", WSAGetLastError());
return 1;
}
return 0;
}