我正在实现一个简单的多线程FTP客户端服务器,我面临一个对我来说很奇怪的问题(因为我不是C ++和线程的主人)。
我写的代码正常工作,直到我#include <thread>
。
一旦我包含线程类,程序就会在listen上失败并给出10022错误。 (我还没有完成与线程相关的任何事情,只能导入)。
以下是代码。该方法从main()。
调用#include <winsock2.h>
#include <ws2tcpip.h>
#include <process.h>
#include <winsock.h>
#include <iostream>
#include <windows.h>
#include <fstream>
#include <string>
#include <stdio.h>
#include <time.h>
#include <thread>
using namespace std;
void initializeSockets()
{
try{
logEvents("SERVER", "Initializing the server");
WSADATA wsadata;
if (WSAStartup(0x0202,&wsadata)!=0){
cout<<"Error in starting WSAStartup()\n";
logEvents("SERVER", "Error in starting WSAStartup()");
}else{
logEvents("SERVER", "WSAStartup was suuccessful");
}
gethostname(localhost,20);
cout<<"hostname: "<<localhost<< endl;
if((hp=gethostbyname(localhost)) == NULL) {
cout << "gethostbyname() cannot get local host info?"
<< WSAGetLastError() << endl;
logEvents("SERVER", "Cannot get local host info. Exiting....");
exit(1);
}
//Create the server socket
if((serverSocket = socket(AF_INET,SOCK_STREAM,0))==INVALID_SOCKET)
throw "can't initialize socket";
//Fill-in Server Port and Address info.
serverSocketAddr.sin_family = AF_INET;
serverSocketAddr.sin_port = htons(port);
serverSocketAddr.sin_addr.s_addr = htonl(INADDR_ANY);
//Bind the server port
if (bind(serverSocket,(LPSOCKADDR)&serverSocketAddr,sizeof(serverSocketAddr)) == SOCKET_ERROR)
throw "can't bind the socket";
cout << "Bind was successful" << endl;
logEvents("SERVER", "Socket bound successfully.");
if(listen(serverSocket,10) == SOCKET_ERROR)
throw "couldn't set up listen on socket";
else
cout << "Listen was successful" << endl;
logEvents("SERVER", "Socket now listening...");
//Connection request accepted.
acceptUserConnections();
}
catch(char* desc)
{
cerr<<str<<WSAGetLastError()<<endl;
logEvents("SERVER", desc);
}
logEvents("SERVER", "Closing client socket...");
closesocket(clientSocket);
logEvents("SERVER", "Closed. \n Closing server socket...");
closesocket(serverSocket);
logEvents("SERVER", "Closed. Performing cleanup...");
WSACleanup();
}
int main(void){
initializeSockets();
return 0;
}
我已阅读帖子Winsock Error 10022 on Listen,但我不认为这可以解决我的问题。
答案 0 :(得分:3)
错误10022是WSAEINVAL
。 listen()
的{{3}}明确指出:
WSAEINVAL
套接字尚未绑定绑定。
添加#include <thread>
后代码停止工作的原因是因为您对bind()
的调用被更改为不再调用WinSock的documentation函数,而是调用STL的using namespace std
3}}功能。您的using namespace std
声明掩盖了该问题(这是using namespace std
如此错误练习的众多原因之一 - 教会自己停止使用它!)。
所以你需要:
摆脱bind()
。
使用全局命名空间限定if (::bind(...) == SOCKET_ERROR)
,因此它调用WinSock的函数:
{{1}}