从C中读取客户端的所有行

时间:2013-11-30 18:08:10

标签: c string sockets client readline

我想从客户端读取和处理所有行,但似乎一次只读取一行。我认为有一个循环,而有读取数据会读取它,但似乎并非如此。 如果读取不完整,我将在下一步中继续关闭该索引。

我有这样的事情:

if (select(maxfd + 1, &fdlist, NULL, NULL, NULL) < 0) {
    perror("select");
} else {
    if (FD_ISSET(listenfd, &fdlist)) {
        newclientconnection();
    }

    // see which clients have activity
    for (p = head; p; p = p->next) {
        if (FD_ISSET(p->fd, &fdlist)) {
            // want to read all lines from client
            while ((n = read(p->fd, p->buf + lastindex, MAX-p->lastindex) > 0) {
                p->lastindex += n;          
            }
            if (n==0) {
                removeclient(p);
            } 

            // want to process all the lines
            process(p->buf);
    } 
}

1 个答案:

答案 0 :(得分:1)

你在这一行中有阻止:

while ((n = read(p->fd, p->buf + lastindex, MAX-p->lastindex) > 0))

在最后一次迭代中,while cond。等待来自read的输入。但输入已经读过。所以,等待新的输入。

如果您假设您获得的数据大于缓冲区(因此您将read置于while条件),则需要为{{1}定义超时(select等) } OR 定义特殊符号(例如“\ r \ n \ r \ n”)以确定“这是数据的结尾”。否则,read循环将永远等待更多数据。