c++ - 一次发送一些字节

标签 c++ c

我正在尝试找出从字符串 ech time 发送一定量文本的方法,直到到达字符串末尾,例如:

const char* the_string = "你好,世界,我很高兴认识你们大家。让我们成为 friend ,或者更多,但同样如此"

输出: Hello World

输出:,我很高兴认识你们。

输出:成为 friend 或者更多

输出:,但同样如此

停止:不再发送字节。

这个问题我已经搜索过谷歌,但不明白这些例子,我花了4天试图找到一个好方法,而且一次发送5个字节,但如果少了,然后发送它们直到你到达字符串的末尾。

请帮助我,我会接受 C 或 C++ 方式,只要它有效并且解释得很好。

最佳答案

根据评论中的讨论,我相信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 );

希望这可以帮助您实现您想要的目标。

关于c++ - 一次发送一些字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10972580/

相关文章:

c++ - std::basic_string<_CharT> 字符串的最大长度

c - 套接字编程中的段错误

c - ARToolkit 使用静止图像

c - int 数据类型的意外输出

c - 头文件结构中的链接器错误

c++ - boost::geometry 3D 多边形相交编译错误

c++ - 优化器会根据编译时常量推导出数学表达式吗?

c++ - const char * 数组中的元素数

c - 为什么我的函数在完成时不再调用自身(递归)?

c++ - C++ 中 vector 的析构函数调用