【问题标题】:reading all lines from client in C在 C 中从客户端读取所有行
【发布时间】:2013-11-30 18:08:09
【问题描述】:

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

我有这样的事情:

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);
    } 
}

【问题讨论】:

    标签: c string sockets client readline


    【解决方案1】:

    你在这行有阻塞:

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

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

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

    【讨论】:

    • 或者用O_NONBLOCK使文件描述符非阻塞?
    • @JonathanLeffler 当然!有几个选项,这就是我写“等”的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    相关资源
    最近更新 更多