Reading from a socket until certain character is in buffer

こ雲淡風輕ζ 提交于 2019-12-11 09:38:00

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/9398436/reading-from-a-socket-until-certain-character-is-in-buffer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!