HANDLE ComPort = (HANDLE)CompletionPort;
DWORD BytesTransferred;
//LPOVERLAPPED Overlapped;
LPPER_HANDLE_DATA PerHandleData;
LPPER_IO_OPERATION_DATA PerIoData;
DWORD SendBytes,RecvBytes;
DWORD Flags = 0;
BOOL bT;
while(TRUE)
{
//等待完成端口上SOCKET的完成
cout<<"["<<GetCurrentProcessId()<<":"<<GetCurrentThreadId()<<"]"<<":等待完成端口上SOCKET的完成"<<endl;
bT = GetQueuedCompletionStatus(ComPort,
&BytesTransferred,(LPDWORD)&PerHandleData,
(LPOVERLAPPED *)&PerIoData,INFINITE);
//检查是否有错误产生
if(BytesTransferred == 0 &&
(PerIoData->OperationType == RECV_POSTED ||
PerIoData->OperationType == SEND_POSTED))
{
//关闭SOCKET
cout<<"["<<GetCurrentProcessId()<<":"<<GetCurrentThreadId()<<"]"<<PerHandleData->sock<<"SOCKET关闭"<<endl;
closesocket(PerHandleData->sock);
free(PerHandleData);
free(PerIoData);
continue;
}
//如果结束socket后做了其他事情,费时间,那么...要么优化其他事情,转移到其他地方去做.要么不适用IOCP.
//Sleep(1000);
//为请求服务
if(PerIoData->OperationType == RECV_POSTED)
{
//处理
cout<<"["<<GetCurrentProcessId()<<":"<<GetCurrentThreadId()<<"]"<<"接收处理"<<endl;
cout<<"["<<GetCurrentProcessId()<<":"<<GetCurrentThreadId()<<"]"<<PerHandleData->sock<<" SOCKET :"<<PerIoData->Buff<<endl;
//回应客户端
ZeroMemory(PerIoData->Buff,24);
//#define _CRT_SECURE_NO_WARNINGS 1
//strcpy(PerIoData->Buff,"OK");
strcpy_s(PerIoData->Buff,"OK");
Flags = 0;
ZeroMemory((LPVOID)&(PerIoData->Overlapped),sizeof(OVERLAPPED));
PerIoData->DataBuff.len = 2;
PerIoData->DataBuff.buf = PerIoData->Buff;
PerIoData->OperationType = SEND_POSTED;
WSASend(PerHandleData->sock,&(PerIoData->DataBuff),
1,&SendBytes,0,&(PerIoData->Overlapped),NULL);
}
else //if(PerIoData->OperationType == SEND_POSTED)
{
//发送时的处理
cout<<"["<<GetCurrentProcessId()<<":"<<setfill('0')<<setw(4)<<GetCurrentThreadId()<<"]"<<"发送处理"<<endl;
Flags = 0;
ZeroMemory((LPVOID)&(PerIoData->Overlapped),sizeof(OVERLAPPED));
ZeroMemory(PerIoData->Buff,24);
PerIoData->DataBuff.len = 24;
PerIoData->DataBuff.buf = PerIoData->Buff;
PerIoData->OperationType = RECV_POSTED;
WSARecv(PerHandleData->sock,&(PerIoData->DataBuff),
1,&RecvBytes,&Flags,&(PerIoData->Overlapped),NULL);
}
}