DataChunk chunk;
char tmpPacket[8192];
short dataLength;
bool isHead = true;
unsigned short tmpLength, offset;
recvThreadNum++;
//cout<<"RecvAndSaveInBuf-"<<tmpIterator->second.sockTCP<<": has entered one thread!!"<<endl;
while(1){
dataLength = recv(tmpIterator->second.sockTCP, tmpPacket, isHead ? sizeof(DataChunk) : chunk.length, MSG_WAITALL);
//檢查是否接收到完整封包, 因若其他thread之recv()返回error時會造成其他thread之recv()當下接收資料不完整, 導致後續資料完全錯亂
tmpLength = isHead ? sizeof(DataChunk) - dataLength : chunk.length - dataLength;
offset = dataLength;
while(tmpLength != 0){
dataLength = recv(tmpIterator->second.sockTCP, tmpPacket + offset, tmpLength, MSG_WAITALL);
if(dataLength == 0) break;
tmpLength -= dataLength;
offset += dataLength;
}
//getsockopt(pPair.second.sockTCP, IPPROTO_TCP, TCP_INFO, &info, (socklen_t*)&infolen);
//cout<<"RecvAndSaveInBuf: "<<pPair.second.sockTCP<<": "<<info.tcpi_rcv_rtt<<endl;
if(dataLength <= 0){
shutdown(tmpIterator->second.sockTCP, 2);
close(tmpIterator->second.sockTCP);
cout<<"RecvAndSaveInBuf-"<<tmpIterator->second.sockTCP<<": recv() data failed: "<<strerror(errno)<<endl;
break;
}
if(isHead){
memcpy((char*)&chunk, tmpPacket, sizeof(DataChunk));
isHead = false;
}
else{
chunk.data = tmpPacket;
if(chunk.state == INITPKG){
while(1){
map<sockaddr_in, Link>::iterator index = LinksTable.begin();
for(; index != LinksTable.end(); index++){
if(index->second.inf.inf_name != ""){
index->second.inf.inf_name = CharToInf(*chunk.data);
index->second.timer = *(timeval*)(chunk.data + sizeof(char));
}
}
if(index == LinksTable.end()){
cout<<"RecvAndSaveInBuf-"<<tmpIterator->second.sockTCP<<": Cannot find the interface in LinksTable\n";
continue;
}
else{
break;
}
}
}
else if(chunk.state == CTRLPKG){
unsigned short index, length = chunk.length - sizeof(timeval);
if(TimevalCompare(*(timeval*)(chunk.data + length), existAddrTimeStamp) != 1){
isHead = true;
continue;
}
existAddrTimeStamp = *(timeval*)(chunk.data + length);
cout<<"RecvAndSaveInBuf-"<<tmpIterator->second.sockTCP<<": existAddr: ";
for(int i = 0; i < (int)(chunk.length - sizeof(timeval)); i++){
cout<<CharToInf(chunk.data[i]);
if(i != (chunk.length - sizeof(timeval) - 1)){
cout<<" - ";
}
}
cout<<endl;
pthread_mutex_lock(&hLinks);
for(map<sockaddr_in, Link>::iterator i = LinksTable.begin(); i != LinksTable.end(); i++){
for(index = 0; index < length; index++){
if(i->second.inf.inf_name == CharToInf(chunk.data[index])){
break;
}
}
if(index == length){
shutdown(i->second.sockTCP, 2);
close(i->second.sockTCP);
shutdown(i->second.hbSockUDP, 2);
close(i->second.hbSockUDP);
}
}
pthread_mutex_unlock(&hLinks);
isHead = true;
continue;
}