@whiteflags
You got me, I rewrote it with std::string functions.
@Elysia
You are right about the size issue and its been bothering me how to solve this. I went with your proposition.
@laserlight
"In my opinion, if you want to design ReceiveDataWithHeader to have a flexible interface to cater for buffers of different sizes..."
I hope you were talking about this solution that I post here otherwise I dont follow what you are saying, obviously I'm not on your level of knowledge.
Code:
in main()
{
vector< char > big( 5000, '\0' );
ReceiveDataWithHeader(AcceptSocket, &big.at( 0 ), big.size());
}
// size of data in header
int ReceiveDataWithHeader(SOCKET Socket, char* Buf, size_t len)
{
bool iGetSize = 1;
short iReceived = 0;
unsigned long DataSize=0, TotalSize=1;
unsigned long Total=0, Digits=0;
string str;
vector<string>Tokens;
while(TotalSize)
{
iReceived = recv(Socket, Buf, len, 0);
if(iReceived > 0)
{
str += Buf;
if(iGetSize)
Total += iReceived;
else
TotalSize -= iReceived;
if(iGetSize)
{
size_t found=str.find_first_of("$");
if(found!=string::npos)
{
split(str, '$', Tokens);
// got DataSize
DataSize=atoi(Tokens[0].c_str());
Digits = GetNumberOfDigits(DataSize);
cout << "Digits " << Digits << endl;
// NumberOfDigits + $ + DataSize
TotalSize = Digits + 1 + DataSize;
// substruct all that we got until now
TotalSize -= Total;
// dont come here anymore
iGetSize = 0;
}
}
cout << "TotalSize " << TotalSize << endl;
}
else if ( iReceived == 0 )
{
printf("ReceiveDataWithHeader Connection closed\n");
return 1;
}
else
{
ReportError("ReceiveDataWithHeader");
return 1;
}
}
split(str, '$', Tokens);
strcpy(Buf, Tokens[1].c_str());
return 0;
}
vector<string> &split(const string &str,
char delim,
vector<string> &elems)
{
// first token
string item = str.substr(0,str.find(str.find('$')));
elems.push_back(item);
// second token
size_t found=str.find_first_of(delim);
elems.push_back(&str[found+1]);
return elems;
}