Это же больная тема всех программистов !
Что-то мне подсказывает, что сейчас посыпиться...
Ладно, привожу пример, по моему разумению, "плохого" и "хорошего" исходника:
std::string HexToBuf(const std::string& hexString)
{
if (hexString.length() % 2 != 0 )
return "";//throw CException(BASIC_ERROR_LINE__,__FILE_"Wrong hex value: %s", hexString.c_str());
if (hexString.length() >= 1024)
return "";//throw CException(BASIC_ERROR_LINE__,__FILE_"Wrong hex value: %s", hexString.c_str());
char buf[1024];
memset(buf,0,sizeof(buf));
unsigned char* bb = (unsigned char*)buf;
for (unsigned int i = 0; i < hexString.length(); i += 2)
{
unsigned char c = hexString[i];
if (! isdigit(c) && ! ('a' <= c && c <= 'f') && ! ('A' <= c && c <= 'F'))
return false;
*bb = (isdigit(c) ? c - '0' :
((('a' <= c && c <= 'f') ? c - 'a' : c - 'A')) + 10) << 4;
c = hexString[i + 1];
if (! isdigit(c) && ! ('a' <= c && c <= 'f') && ! ('A' <= c && c <= 'F'))
return false;
*bb++ |= isdigit(c) ? c - '0' :
((('a' <= c && c <= 'f') ? c - 'a' : c - 'A') + 10);
}
return std::string(buf,hexString.length()/2);
}
---
void TCPConnector::Reader( void* _me )
{
while(1)
{
printf( "Reading a packet...\n" );
TCPConnector* me = (TCPConnector*)_me;
if( !me->m_reader_ready.Get() )
{
_beginthread( WaitForConnectReader, 0, _me );
return;
}
short packetSize;
int rcvSz;
if( ( rcvSz = recv( me->m_sock_reader, (char*)&packetSize, sizeof( short ), 0 ) ) != SOCKET_ERROR )
{
if( packetSize < 0 )
{
printf( "The packet size is (%X). Connect is broken !\n", packetSize );
closesocket( me->m_sock_reader );
me->m_reader_ready.Set( false );
_beginthread( WaitForConnectReader, 0, _me );
return;
}
if( packetSize == 0 )
{
printf( "The packet size is (%X) ! Skipping...\n", packetSize );
Sleep(1000);
_beginthread( Reader, 0, _me );
return;
}
}
else
{
printf( "The error while recive. The connect is broken !\n" );
closesocket( me->m_sock_reader );
me->m_reader_ready.Set( false );
_beginthread( WaitForConnectReader, 0, _me );
return;
}
char* buffer = new char[ packetSize ];
int recSize = 0;
int offset = packetSize;
int tmpPS = packetSize;
char *ptr = buffer;
while( recSize < tmpPS)
{
tmpPS -= recSize;
ptr += recSize;
offset -= recSize;
recSize = recv( me->m_sock_reader, ptr, offset, 0 );
if( recSize == SOCKET_ERROR )
{
printf( "The error while recive. The connect was broken !\n" );
closesocket( me->m_sock_reader );
me->m_reader_ready.Set( false );
_beginthread( WaitForConnectReader, 0, _me );
delete[] buffer;
return;
}
}
me->m_Reciver( buffer, packetSize );
delete[] buffer;
}// while(1)
}
---
Думаю комментарии излишни.
|