c - 用 C 读取客户端的所有行

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

最佳答案

您在该行中阻塞了:

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

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

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

关于c - 用 C 读取客户端的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20303781/

相关文章:

访问环境变量的C代码

java - 在 | 上拆分字符串Java 中的(管道)

sockets - 接收 "Destination Unreachable"数据包时不发送 ICMP 回显请求

node.js - 跨服务器的 NodeJS 匹配

c - TFTP UDP header 校验和失败

c - OpenSSL 使用固定值来生成 Diffie Hellman key

c - 如何理解下面的代码?

c++ - 字符串文字不能有外部链接是否有原因?

java - 使用运算符 + 与使用字符串缓冲区进行字符串连接?

Python 多线程与共享变量