完成端口的使用
这是我参考windows网络编程上写的一个服务器端完成端口的一个例子,但是运行后,可以accept客户端的TCP连接,在客户端send一个11字节的字符串后,服务器端显示错误1:10045,参考的对象类型不支持尝试的操作,这个时候传给WSARecv的Flags变量是没有赋初值的。我把Flags赋初值0,重复运行,显示错误2:句柄无效。我个人感觉好像是我WSAAccept的那个Socket Accept不支持overlap操作,但是我又找不到哪错了,请各位大侠帮忙看看。
int main()
{
SOCKADDR_IN InternetAddr;
SOCKET Listen;
WSADATA wsd;
SYSTEM_INFO SystemInfo;
int ret;
if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)
{
cout<<"unable to load Winsock!\n"<<endl;
return -1;
}
CompletionPort = CreateIoCompletionPort(
INVALID_HANDLE_VALUE, NULL, 0, 0);
GetSystemInfo(&SystemInfo);
for(int i = 0; i < SystemInfo.dwNumberOfProcessors; i++)
{
HANDLE ThreadHandle;
ThreadHandle = CreateThread(NULL, 0,
TCPWorkerThread, CompletionPort,
0, NULL);
CloseHandle(ThreadHandle);
}
Listen = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED);
InternetAddr.sin_family = AF_INET;
InternetAddr.sin_addr.s_addr = htonl(INADDR_ANY);
InternetAddr.sin_port = htons(2001);
bind(Listen, (PSOCKADDR) &InternetAddr,
sizeof(InternetAddr));
listen(Listen, 5);
while(TRUE)
{
SOCKADDR_IN saRemote;
SOCKET Accept;
int RemoteLen;
DWORD RecvBytes;
RemoteLen = sizeof(saRemote);
Accept = WSAAccept(Listen, (SOCKADDR *)&saRemote,
&RemoteLen,NULL,0);
int ii = 9;//////////////////传这个只是为了实验而已
CreateIoCompletionPort((HANDLE) Accept,
CompletionPort, (DWORD) &ii, 0);
DWORD Flags;//////////////////////关于Flags需要赋初值吗?赋0还是?
WSABUF b;
b.buf = new char[32];
b.len = 32;
OVERLAPPED ol;
ret = WSARecv(Accept, &b,1,&RecvBytes,&Flags, &ol, NULL);
if (ret == SOCKET_ERROR)
{
cout<< GetErrorText()<<endl;
return -1;
}
}
return 1;
}