嘿...我使用 I/O 完成端口和 winsock 创建了一个小型测试服务器。我可以成功连接套接字句柄并将其与完成端口相关联。但我不知道如何将用户定义的数据结构传递到工作线程......
到目前为止,我尝试的是(ULONG_PTR)&structure as
在关联调用中将用户结构作为完成键传递,CreateIoCompletionPort()
但这不起作用。
现在我尝试定义自己的 OVERLAPPED 结构并使用 CONTAINING_RECORD(),如此处所述http://msdn.microsoft.com/en-us/magazine/cc302334.aspx和http://msdn.microsoft.com/en-us /杂志/bb985148.aspx。但这也行不通。(我得到 pHelper 内容的怪异值)
所以我的问题是:如何使用 WSARecv()、GetQueuedCompletionStatus() 和 Completion 数据包或 OVERLAPPED 结构将数据传递给工作线程?
编辑:我怎样才能成功传输“每个连接数据”?...似乎我做错了艺术(如上面两个链接中所述)。
这是我的代码:(是的,它很丑,也是唯一的测试代码)
struct helper
{
SOCKET m_sock;
unsigned int m_key;
OVERLAPPED over;
};
///////
SOCKET newSock = INVALID_SOCKET;
WSABUF wsabuffer;
char cbuf[250];
wsabuffer.buf = cbuf;
wsabuffer.len = 250;
DWORD flags, bytesrecvd;
while(true)
{
newSock = accept(AcceptorSock, NULL, NULL);
if(newSock == INVALID_SOCKET)
ErrorAbort("could not accept a connection");
//associate socket with the CP
if(CreateIoCompletionPort((HANDLE)newSock, hCompletionPort, 3,0) != hCompletionPort)
ErrorAbort("Wrong port associated with the connection");
else
cout << "New Connection made and associated\n";
helper* pHelper = new helper;
pHelper->m_key = 3;
pHelper->m_sock = newSock;
memset(&(pHelper->over), 0, sizeof(OVERLAPPED));
flags = 0;
bytesrecvd = 0;
if(WSARecv(newSock, &wsabuffer, 1, NULL, &flags, (OVERLAPPED*)pHelper, NULL) != 0)
{
if(WSAGetLastError() != WSA_IO_PENDING)
ErrorAbort("WSARecv didnt work");
}
}
//Cleanup
CloseHandle(hCompletionPort);
cin.get();
return 0;
}
DWORD WINAPI ThreadProc(HANDLE h)
{
DWORD dwNumberOfBytes = 0;
OVERLAPPED* pOver = nullptr;
helper* pHelper = nullptr;
WSABUF RecvBuf;
char cBuffer[250];
RecvBuf.buf = cBuffer;
RecvBuf.len = 250;
DWORD dwRecvBytes = 0;
DWORD dwFlags = 0;
ULONG_PTR Key = 0;
GetQueuedCompletionStatus(h, &dwNumberOfBytes, &Key, &pOver, INFINITE);
//Extract helper
pHelper = (helper*)CONTAINING_RECORD(pOver, helper, over);
cout << "Received Overlapped item" << endl;
if(WSARecv(pHelper->m_sock, &RecvBuf, 1, &dwRecvBytes, &dwFlags, pOver, NULL) != 0)
cout << "Could not receive data\n";
else
cout << "Data Received: " << RecvBuf.buf << endl;
ExitThread(0);
}