IOCP C ++ TCP客户端
|
我在实现TCP IOCP客户端时遇到了一些麻烦。我已经在Mac OSX上实现了kqueue,所以希望在Windows上做类似的事情,我的理解是IOCP是最接近的东西。主要问题是GetCompetetionStatus从不返回,并且总是超时。我假设在创建要监视的句柄时缺少了某些内容,但不确定是什么。到目前为止,这是我到达的地方:
我的连接例程:(为清楚起见,删除了一些错误处理)
struct sockaddr_in server;
struct hostent *hp;
SOCKET sckfd;
WSADATA wsaData;
int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
if ((hp = gethostbyname(host)) == NULL)
return NULL;
WSASocket(AF_INET,SOCK_STREAM,0,NULL,0,WSA_FLAG_OVERLAPPED)
if ((sckfd = WSASocket(AF_INET,SOCK_STREAM,0, NULL, 0, WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET)
{
printf(\"Error at socket(): Socket\\n\");
WSACleanup();
return NULL;
}
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr = *((struct in_addr *)hp->h_addr);
memset(&(server.sin_zero), 0, 8);
//non zero means non blocking. 0 is blocking.
u_long iMode = -1;
iResult = ioctlsocket(sckfd, FIONBIO, &iMode);
if (iResult != NO_ERROR)
printf(\"ioctlsocket failed with error: %ld\\n\", iResult);
HANDLE hNewIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, ulKey, 0);
CreateIoCompletionPort((HANDLE)sckfd, hNewIOCP , ulKey, 0);
connect(sckfd, (struct sockaddr *)&server, sizeof(struct sockaddr));
//WSAConnect(sckfd, (struct sockaddr *)&server, sizeof(struct sockaddr),NULL,NULL,NULL,NULL);
return sckfd;
这是发送例程:(为了清楚起见,还删除了一些错误处理)
IOPortConnect(int ServerSocket,int timeout,string& data){
char buf[BUFSIZE];
strcpy(buf,data.c_str());
WSABUF buffer = { BUFSIZE,buf };
DWORD bytes_recvd;
int r;
ULONG_PTR ulKey = 0;
OVERLAPPED overlapped;
OVERLAPPED* pov = NULL;
HANDLE port;
HANDLE hNewIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, ulKey, 0);
CreateIoCompletionPort((HANDLE)ServerSocket, hNewIOCP , ulKey, 0);
BOOL get = GetQueuedCompletionStatus(hNewIOCP,&bytes_recvd,&ulKey,&pov,timeout*1000);
if(!get)
printf(\"waiton server failed. Error: %d\\n\",WSAGetLastError());
if(!pov)
printf(\"waiton server failed. Error: %d\\n\",WSAGetLastError());
port = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, (u_long)0, 0);
SecureZeroMemory((PVOID) & overlapped, sizeof (WSAOVERLAPPED));
r = WSASend(ServerSocket, &buffer, 1, &bytes_recvd, NULL, &overlapped, NULL);
printf(\"WSA returned: %d WSALastError: %d\\n\",r,WSAGetLastError());
if(r != 0)
{
printf(\"WSASend failed %d\\n\",GetLastError());
printf(\"Bytes transfered: %d\\n\",bytes_recvd);
}
if (WSAGetLastError() == WSA_IO_PENDING)
printf(\"we are async.\\n\");
CreateIoCompletionPort(port, &overlapped.hEvent,ulKey, 0);
BOOL test = GetQueuedCompletionStatus(port,&bytes_recvd,&ulKey,&pov,timeout*1000);
CloseHandle(port);
return true;
}
任何见识将不胜感激。
没有找到相关结果
已邀请:
2 个回复
帆攀缺锯欧
盛虱