阅读不止一个“消息"从接收() [英] Reading more than one "message" from recv()

查看:27
本文介绍了阅读不止一个“消息"从接收()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

完全有可能使用 recv() 调用将多个单独的消息"(例如 2 个 send())读入缓冲区.

It is entirely possible that more than one separate "messages" (e.g. 2 send()s) could be read into a buffer using the recv() call.

在这种情况下,一旦您意识到缓冲区中的数据超出了您的需要,您将如何将第二条消息放回 recv() 缓冲区?

In such a case, how would you put the second message back into the recv() buffer, once you've realised you have more data in your buffer than you need?

例如

所有消息都以一个字节表示其长度.我需要继续接收,直到正确数量的字节被读入缓冲区,但不能继续接收.

All messages are prepended with a byte dictating their length. I need to keep receiving until the correct number of bytes has been read into a buffer, but not continue beyond that point.

一个想法是做一个 recv() 来建立消息长度,然后创建一个具有该大小的缓冲区.我不知道如果数据不适合缓冲区会发生什么.

One idea is to do one recv() to establish message length, and then create a buffer with that size. I don't know what would happen though to data which doesn't fit into the buffer.

推荐答案

如果您想接收固定尺寸,您可以这样做:

If you have a fixed size you want to receive you could do something like this:

ssize_t recv_all(int socket, char *buffer_ptr, size_t bytes_to_recv)
{
    size_t original_bytes_to_recv = bytes_to_recv;

    // Continue looping while there are still bytes to receive
    while (bytes_to_recv > 0)
    {
        ssize_t ret = recv(socket, buffer_ptr, bytes_to_recv, 0);
        if (ret <= 0)
        {
            // Error or connection closed
            return ret;
        }

        // We have received ret bytes
        bytes_to_recv -= ret;  // Decrease size to receive for next iteration
        buffer_ptr += ret;     // Increase pointer to point to the next part of the buffer
    }

    return original_bytes_to_recv;  // Now all data have been received
}

简单地用作

// Somewhere above we have received the size of the data to receive...

// Our data buffer
char buffer[the_full_size_of_data];

// Receive all data
recv_all(socket, buffer, sizeof buffer);  // TODO: Add error checking

[请注意,我对套接字使用了像 ssize_tint 这样的 POSIX 类型.修改以适合您的系统(例如,SOCKET 用于 Windows 上的套接字).]

[Note that I use POSIX types like ssize_t and int for the sockets. Modify to fit your system (e.g. SOCKET for the socket on Windows).]

这篇关于阅读不止一个“消息"从接收()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆