简体   繁体   English

从套接字读取直到某些字符在缓冲区中

[英]Reading from a socket until certain character is in buffer

I am trying to read from a socket into a buffer until a certain character is reached using read(fd, buf, BUFFLEN) . 我试图从套接字读入缓冲区,直到使用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? 是否可以将read调用置于循环中,以便在到达此空行时停止,然后在需要时可以读取其余信息?

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. 如果要读取新发送的数据,则必须在某些时候读取任何未读数据。

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. 我认为最好的实现方法是保持循环从套接字读取,同时启动另一个进程/线程以在收到空白之类的消息时执行所需的任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM