从套接字读取直到缓冲区中有某个字符

发布于 2025-01-08 10:57:02 字数 149 浏览 1 评论 0原文

我正在尝试从套接字读取到缓冲区,直到使用 read(fd, buf, BUFFLEN) 到达某个字符。

例如,套接字将在一次读取调用中接收由空行分隔的两批信息。

是否可以将读取调用放入循环中,以便在到达此空白行时停止,然后在需要时可以稍后读取其余信息?

I am trying to read from a socket into a buffer until a certain character is reached using read(fd, buf, BUFFLEN).

For example, the socket will receive two lots of information separated by a blank line in one read call.

Is it possible to put the read call in a loop so it stops when it reaches this blank line, then it can read the rest of the information later if it is required?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

╰沐子 2025-01-15 10:57:02

一种简单的方法是一次读取一个字节,直到前一个字节和当前字节是换行符,因为两个连续的换行符是一个空行:

size_t buf_idx = 0;
char buf[BUFFLEN] = { 0 };

while (buf_idx < BUFFLEN && 1 == read(fd, &buf[buf_idx], 1)
{
    if (buf_idx > 0          && 
        '\n' == buf[buf_idx] &&
        '\n' == buf[buf_idx - 1])
    {
        break;
    }
    buf_idx++;
}

任何未读的数据都必须在某个时刻被读取如果要读取新发送的数据。

A simple approach would be to read a single byte at a time until the previous byte and the current byte are new-line characters, as two consecutive new-line characters is a blank line:

size_t buf_idx = 0;
char buf[BUFFLEN] = { 0 };

while (buf_idx < BUFFLEN && 1 == read(fd, &buf[buf_idx], 1)
{
    if (buf_idx > 0          && 
        '\n' == buf[buf_idx] &&
        '\n' == buf[buf_idx - 1])
    {
        break;
    }
    buf_idx++;
}

Any unread data will have to be read at some point if newly sent data is to be read.

蘸点软妹酱 2025-01-15 10:57:02

如果以后想访问这些信息,仍然需要从套接字中读取,否则会丢失。我认为最好的实现是继续从套接字循环读取,同时启动另一个进程/线程以在收到空白时执行您想要的任何操作。

You still need to read from the socket if you want to access this information later, otherwise it will be lost. I think best implementation would be to keep looping reading from the socket, while another process/thread is launched to perform any operation you want when a blank like is received.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文