从套接字缓冲区读取一行行 [英] read line by line from a socket buffer

查看:138
本文介绍了从套接字缓冲区读取一行行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我需要的帮助:我想编写从通过从第三个参数获得一个套接字缓冲区行读取线)函数读取(函数从 unistd.h中头。

Well, I need to help: I want to write a function that read line by line from a socket buffer obtained from third parameter from read() function from unistd.h header.

我已经写了这个:

int sgetline(int fd, char ** out)
{
    int buf_size = 128;
    int bytesloaded = 0;
    char buf[2];
    char * buffer = malloc(buf_size);
    char * newbuf;
    int size = 0;

    assert(NULL != buffer);

    while( read(fd, buf, 1) > 0 )
    {
        strcat(buffer, buf);
        buf[1] = '\0';
        bytesloaded += strlen(buf);
        size = size + buf_size;

        if(buf[0] == '\n')
        {
            *out = buffer; 
            return bytesloaded;
        }

        if(bytesloaded >= size)
        {
            size = size + buf_size;
            newbuf = realloc(buffer, size);

            if(NULL != newbuf)
            {
                buffer = newbuf;
            }
            else 
            {
                printf("sgetline() allocation failed!\n");
                exit(1);
            }
        }
    }

    *out = buffer;
    return bytesloaded;
}

但是我有一些问题与此功能,例如,如果输入是这样的:

but I have some problems with this function, for example, if the input is something like:

HTTP/1.1 301 Moved Permanently\r\n
Cache-Control:no-cache\r\n
Content-Length:0\r\n
Location\r\nhttp://bing.com/\r\n
\r\n\r\n

和我做

int sockfd = socket( ... );
//....
char* tbuf;
while(sgetline(sockfd, &tbuf) > 0)
{
    if(strcmp(tbuf,"\r\n\r\n") == 0)
    {
       printf("End of Headers detected.\n");
    }
}

以上的C应用程序不输出页眉结束检测。。为什么?如何解决这一问题?为改善这一功能的提示是非常AP preciated。提前致谢。 :)

the above C application does not output "End of Header detected.". Why? how to fix this? tips for improve this functions are very appreciated. Thanks in advance. :)

推荐答案

您正在为自己的事情变得更加困难比他们需要。你真的不需要做strcats让你的当前位置添加的每个读取读取单个字符。

You are making things more difficult for yourself than they need to be. You really don't need to do strcats to get the single character you read on each read added at the current position.

但你的错误是,一旦它看到一个\\ N,因此字符串返回不能包含第一个\\ N按照什么。例程返回

But your bug is that the routine returns as soon as it sees a \n, so the string it returns can never contain anything following the first \n.

这篇关于从套接字缓冲区读取一行行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆