【问题标题】:How can I stop C++ recv() when string read is finished?字符串读取完成后如何停止 C++ recv()?
【发布时间】:2016-06-30 15:47:29
【问题描述】:

我正在读取从 Java 客户端从套接字发送到 C++ 服务器的图像 URL。当服务器检测到 char buffer[] 中存在空字符时,服务器停止读取 recv(),如下面的代码所示:

void * SocketServer::clientController(void *obj)
{
    // Retrieve client connection information
    dataSocket *data = (dataSocket*) obj;

    // Receive data from a client step by step and append data in String message
    string message;
    int bytes = 0;
    do
    {
        char buffer[12] = {0};
        bytes = recv(data->descriptor, buffer, 12, 0);

        if (bytes > 0) // Build message
        {
            message.append(buffer, bytes);
            cout << "Message: " << message << endl;
        }
        else // Error when receiving it
            cout << "Error receiving image URL" << endl;


        // Check if we are finished reading the image link
        unsigned int i = 0;
        bool finished = false;
        while (i < sizeof(buffer) / sizeof(buffer[0]) && !finished)
        {
            finished = buffer[i] == '\0';
            i++;
        }

        if (finished)
            break;

    }
    while (bytes > 0);

    cout << message << endl;

    close(data->descriptor);
    pthread_exit(NULL);
}

有没有更好、更优雅的方法来做到这一点?

我读到了先发送 URL 的大小,但我不知道如何用它来停止 recv()。我想这是通过计算接收到的字节数来完成的,直到达到 URL 的大小。那一刻,我们应该读完了。

另一种方法可能是关闭 Java 套接字,这样 recv() 将返回 -1 并结束循环。但是,考虑到我的 Java 客户端等待来自 C++ 服务器的响应,关闭套接字然后重新打开它似乎不是一个合适的选择。

谢谢, 赫克托

【问题讨论】:

    标签: c++ sockets recv


    【解决方案1】:

    除了你的缓冲区有一个不寻常的大小(通常选择 2 的幂,所以 8、16、32,...)而且它看起来有点小,你的意图,你的方法对我来说似乎很好:

    我假设您的 java 客户端将发送一个以 null 结尾的字符串,然后无论如何都要等待,即。 e.特别是它不会发送任何进一步的数据。因此,在您收到 0 字符后,无论如何都不会再收到任何数据,因此无需为 recv 隐式执行的显式操作而烦恼(recv 通常仅返回可用数据,即使小于缓冲区可能会消耗)。

    请注意,您使用 0 初始化缓冲区,因此如果您检查整个缓冲区(而不是范围 [buffer, buffer + bytes),您可能会检测到误报(如果您在第一次迭代中收到少于 12 个字符)!无论如何,0 字符的检测可以更优雅地完成:

    if(std::find(buffer, buffer + bytes, 0) < buffer + bytes)
    {
        // found the 0 character!
        break;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-05
      • 2012-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      相关资源
      最近更新 更多