写了个最简单的完成端口服务端但是为什么收不到消息?
// IOCP.cpp : Defines the entry point for the console application.#include "stdafx.h"
#include <Winsock2.h>
#pragma comment(lib,"Ws2_32.lib")
struct handleData
{
SOCKET clientsocket;
SOCKADDR_IN clientaddr;
int nOperatorType;
};
struct iOData
{
OVERLAPPED theoverlapped;
WSABUF buff;
char recvbuff[MAXBYTE];
};
void InitWinSock()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 )
{
return;
}
if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2 ) {
WSACleanup( );
return;
}
}
int GetLocalMoShineInfo(SYSTEM_INFO& sysinfo)
{
GetSystemInfo(&sysinfo);
int nCPU = sysinfo.dwNumberOfProcessors;
return nCPU;
}
DWORD WINAPI threadfun(LPVOID lparam)
{
bool bRet;
DWORD dwNumRead;
handleData handledata;
iOData overlappdata;
HANDLE hCompletion = (HANDLE)lparam;
LPOVERLAPPED lpOver = NULL;
while (TRUE)
{
bRet = GetQueuedCompletionStatus(hCompletion,&dwNumRead,(LPDWORD)&handledata,(LPOVERLAPPED*)&overlappdata,INFINITE);
if (bRet==0&&lpOver!=NULL)
{
//closesocket(handledata.clientsocket);
printf("È¡°üʧ°Ü!");
}
else if (bRet!=0)
{
printf("È¡µ½Ò»¸ö°ü!");
}
}
return 0;
}
int main(int argc, char* argv[])
{
InitWinSock();
SOCKET Listens = socket(AF_INET,SOCK_STREAM,0);
if (Listens==INVALID_SOCKET)
{
printf("´´½¨Ì×½Ó×Öʧ°Ü!");
return 0;
}
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(7000);
addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
if (bind(Listens,(sockaddr*)&addr,sizeof(addr)))
{
printf("°ó¶¨Ê§°Ü!");
return 0;
}
HANDLE hIoCptport = CreateIoCompletionPort(INVALID_HANDLE_VALUE,NULL,0,0);
if (hIoCptport==NULL)
{
printf("´´½¨IOÍê³É¶Ë¿Úʧ°Ü!");
return 0;
}
SYSTEM_INFO sysinfo;
int nCPU = GetLocalMoShineInfo(sysinfo);
int nThread = nCPU*2+2;
for (int i = 0;i<nThread;i++)
{
HANDLE handle = CreateThread(NULL,0,threadfun,(LPVOID)hIoCptport,0,0);
if ( handle )
{
CloseHandle(handle);
}
}
listen(Listens,SOMAXCONN);
printf("·þÎñÆ÷Æô¶¯,¿ªÊ¼¼àÌý¡¤¡¤¡¤¡¤¡¤¡¤\r\n");
while (TRUE)
{
struct handleData* pKey = NULL;
sockaddr_in clientaddr;
int clientaddlength = sizeof(clientaddr);
SOCKET clientsock = accept(Listens,(sockaddr*)&clientaddr,&clientaddlength);
printf("ÓÐÈ˽øÀ´ÁË\r\n");
if (clientsock==INVALID_SOCKET)
{
printf("½ÓÊÕʧ°Ü!");
return 0;
}
pKey = new handleData();
if ( pKey )
{
pKey->clientsocket = clientsock;
pKey->clientaddr = clientaddr;
//pKey->nOperatorType = OP_READ;
}
CreateIoCompletionPort((HANDLE)(pKey->clientsocket),hIoCptport,(DWORD)pKey,0);
iOData* poverlapped = new iOData();
if (poverlapped)
{
poverlapped->buff.buf = poverlapped->recvbuff;
poverlapped->buff.len = MAXBYTE;
}
DWORD dwRecv = 0;
DWORD dwFlag = 0;
WSARecv(pKey->clientsocket,&(poverlapped->buff),1,&dwRecv,&dwFlag,&(poverlapped->theoverlapped),NULL);
int nError = GetLastError();
}
return 0;
}