根据评论中的讨论,我相信 OP 正在寻找的是一种能够通过套接字发送全部数据的方式。
使用 C++ 和模板,通过套接字发送任意数据(就本代码示例而言,我将使用 WinSock)相当简单。
通用发送功能:
template <typename T>
int SendData( const T& tDataBuffer, SOCKET sSock )
{
// Make sure the class is trivially copyable:
static_assert( std::is_pod<T>::value && !std::is_pointer<T>::value, "The object type must be trivially copyable" );
char* chPtr = (char*)(&tDataBuffer);
unsigned int iSent = 0;
for( unsigned int iRemaining = sizeof(T); iRemaining > 0; iRemaining -= iSent )
{
iSent = send( sSock, chPtr, iRemaining, 0 );
chPtr += iSent;
if( iSent <= 0 )
{
return iSent;
}
}
return 1;
}
指针重载:
template <typename T>
int SendData( T* const &ptObj, unsigned int iSize, SOCKET sSock )
{
// Make sure the class is trivially copyable:
static_assert( std::is_pod<T>::value, "The object type must be trivially copyable" );
char* chPtr = (char*)ptObj;
unsigned int iSent = 0;
for( unsigned int iRemaining = iSize; iRemaining > 0; iRemaining -= iSent )
{
iSent = send( sSock, chPtr, iRemaining, 0 );
chPtr += iSent;
if( iSent <= 0 )
{
return iSent;
}
}
return 1;
}
专业化std::string
:
template <>
int SendData( const std::string& szString, SOCKET sSock )
{
// Send the size first:
int iResult = SendData( static_cast<unsigned int>(szString.length()) * sizeof(char) + sizeof('\0'), sSock );
if( iResult <= 0 )
return iResult;
iResult = SendData(szString.c_str(), static_cast<unsigned int>(szString.length()) * sizeof(char) + sizeof('\0'), sSock);
return iResult;
}
使用这些功能的示例如下:
std::string szSample = "hello world, i'm happy to meet you all. Let be friends or maybe more, but nothing less";
// Note that this assumes that sSock has already been initialized and your connection has been established:
SendData( szSample, sSock );
希望这可以帮助你实现你想要的。