我正在编写一个bittorrent客户端,需要通过tcp连接联系多个跟踪器。为了做到这一点,我写了一个winsock包装类,如下所示:
class trackerSocket{
public:
~trackerSocket();
int trackerInitialize(string address);
int trackerSend(string getParams);
int trackerRecv();
be_node *responseDict;
bool working;
private:
string address;
string port;
string protocol;
string page;
SOCKET ConnectSocket;
int parseAnnounce(string announce);
int parseTrackerResponse(string response);
};
程序首先为变量分配一个新的trackerSocket类。 trackerInitialize函数在此函数上调用,如果成功,则将类推送到向量以存储所有工作跟踪器。这是trackerInitialize函数:
int trackerSocket::trackerInitialize(string announce){
WSADATA wsaData;
int iResult;
working = true;
iResult = parseAnnounce(announce);
if(iResult != 0){
working = false;
return iResult;
}
//Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if(iResult != 0){
return 1;
}
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
//Resolve the server address and port
iResult = getaddrinfo(address.c_str(), port.c_str(), &hints, &result);
if(iResult != 0){
WSACleanup();
return 1;
}
ConnectSocket = INVALID_SOCKET;
//Attempt to connect to the first address returned by
//the call to getaddrinfo
ptr = result;
do{
//Create a socket for connecting to the server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if(ConnectSocket == INVALID_SOCKET){
ptr = ptr->ai_next;
continue;
}
//Connect to server
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if(iResult != SOCKET_ERROR){
break;
} else {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
ptr = ptr->ai_next;
}
} while(ptr != NULL);
freeaddrinfo(result);
if(ConnectSocket == INVALID_SOCKET){
working = false;
WSACleanup();
return 1;
}
return 0;
}
然后程序执行代码以生成要发送给跟踪器的消息。对于向量中的每个跟踪器类,使用消息调用trackerSend函数,这里是trackerSend函数:
int trackerSocket::trackerSend(string getParams){
int iResult;
ostringstream os;
os << "GET " << page << getParams << " HTTP/1.1\r\n"
<< "Host: " << address << "\r\n"
<< "Accept: text/html\r\n"
<< "\r\n";
string sendBuf = os.str();
//Send tracker request
iResult = send(ConnectSocket, sendBuf.c_str(), strlen(sendBuf.c_str()), 0);
if(iResult == SOCKET_ERROR){
working = false;
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
return 0;
}
每次程序运行时,send函数都会为每个跟踪器返回-1。如果我调用WSAGetLastError()函数,则返回10093.此错误的msdn定义为:
尚未执行成功的WSAStartup。 应用程序未调用WSAStartup或WSAStartup失败。应用程序可能正在访问当前活动任务不拥有的套接字(即尝试在任务之间共享套接字),或者WSACleanup已被调用太多次。
我看不到WSACleanup被调用的次数太多,所以我只能假设套接字不属于当前活动任务(不知道这意味着什么),有人能看到问题吗?
主要程序的一些代码(我在上面已经描述过):
//Store tracker URL's in vector
vector<trackerSocket> trackers;
trackerSocket *temptracker = new trackerSocket();
iResult = temptracker->trackerInitialize(announce);
if(iResult == 0){
trackers.push_back(*temptracker);
}
if(announcelist != NULL){
i = 0;
while(announcelist[i]){
if(strcmp(announcelist[i]->val.l[0]->val.s, announce.c_str()) != 0){
temptracker = new trackerSocket();
iResult = temptracker->trackerInitialize(announcelist[i]->val.l[0]->val.s);
if(iResult == 0){
trackers.push_back(*temptracker);
}
}
i++;
}
}
//Check that at least one of the tracker URL's was valid
if(trackers.size() == 0){
printf("None of the tracker URL's provided were valid.\n");
return 1;
}
//Generate some required values
string peerid = genPeerID();
string peerport = "12345";
int uploaded = 0;
int downloaded = 0;
//Work out how many bytes are left to download
int left = 0;
if(singlefile){
left = length;
} else {
for(i = 0; i < filesinfo.size(); i++){
left += filesinfo[i].length;
}
}
//Send GET Request to tracker
i = 0;
ostringstream os;
string getParams;
string response;
os << "info_hash=" << infohash << "&peer_id=" << peerid << "&port=" << peerport <<
"&uploaded=" << uploaded << "&downloaded=" << downloaded << "&event=started";
getParams = os.str();
do{
iResult = trackers[i].trackerSend(getParams);
if(iResult != 0){
printf("trackerSend %d failed: %d\n", i, iResult);
i++;
continue;
}
} while(i < trackers.size());
答案 0 :(得分:2)
从你的代码中你不应该在send上调用WSACleanup,如果一个跟踪器无法发送你将减少内部计数器,如果它达到0,系统将需要一个你没有调用的新WSAStartup ...... / p>
我建议你只调用一次WSAStartup(例如,在应用程序的开头)并且只调用一次WSACleanup。 (例如申请结束)
答案 1 :(得分:0)
我从代码中休息后设法解决了问题。我相信这个问题在这个问题和答案中有所描述:
C++ vector of objects vs. vector of pointers to objects
你需要了解的关于c ++中的向量的一点是,他们必须使用对象类的复制操作符才能将它们输入到向量中。如果在调用析构函数时自动解除分配这些对象中的内存分配,则可以解释您的问题:您的对象被复制到向量中然后被销毁。
如果在对象类中有指向指定缓冲区的指针,则此对象的副本将指向同一缓冲区(如果使用默认复制运算符)。如果析构函数释放缓冲区,则在调用复制析构函数时,将释放原始缓冲区,因此您的数据将不再可用。
如果使用指针,则不会发生此问题,因为您通过new / destroy控制元素的生命周期,而vector函数仅将指针复制到元素。
更改向量以存储指向trackerSocket类的指针而不仅仅是trackerSocket类的副本并更改向量(。到 - &gt;)中对trackerSocket函数的调用后,问题已成功修复。以下是我所做的更改:
<强>旧强>
vector<trackerSocket> trackers;
trackers.push_back(*temptracker);
trackers[i].trackerSend(getParams);
新强>
vector<trackerSocket*> trackers;
trackers.push_back(temptracker);
trackers[i]->trackerSend(getParams);