C & Libevent : add binary data to output buffer

标签 c binary buffer libevent

我有一个输出 evbuffer,我想用以下数据填充它:

HTTP/1.1 200 OK
Date: Tue, 06 Dec 2011 10:35:08 GMT
Server: Apache/2.2.14 (Ubuntu)
X-Powered-By: PHP/5.3.2-1ubuntu4.9
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 48
Content-Type: text/html

��(�ͱ���I�O����H�����ч��
                          �4�@�

我正在使用evbuffer_add_printf(...)

我有以下 C 回调函数:

static void echo_read_cb(struct bufferevent *bev, void *ctx){
    /* This callback is invoked when there is data to read on bev. */
    struct evbuffer *input = bufferevent_get_input(bev);
    struct evbuffer *output = bufferevent_get_output(bev);

    ...
    char* response=NULL;
    response=applyGetReq(url,data,len);

    int contLen=0;
    contLen=getContentLength(response);

    char* binData=strstr(response,"\r\n\r\n");
    binData=binData+strlen("\r\n\r\n");
    fwrite(binData,sizeof(char),contLen,stdout);
    printf("\n");

    evbuffer_add_printf(output,"%s",binData);   //I want to print binData as binary, not printf!!!
}

所以我有二进制数据指针 (binData) 和长度 (contLen),如何将其打印到输出缓冲区?

提前非常感谢

最佳答案

您无法使用 evbuffer_add_printf 以安全的方式添加二进制数据。尝试 evbuffer_add 函数:

int
evbuffer_add(struct evbuffer *buf, const void *data, size_t datlen)
{
    size_t need = buf->misalign + buf->off + datlen;
    size_t oldoff = buf->off;

    if (buf->totallen < need) {
            if (evbuffer_expand(buf, datlen) == -1)
                    return (-1);
    }

    memcpy(buf->buffer + buf->off, data, datlen);
    buf->off += datlen;

    if (datlen && buf->cb != NULL)
            (*buf->cb)(buf, oldoff, buf->off, buf->cbarg);

    return (0);
}

找不到好的文档,除了源代码之外我见过的最好的文档是:

http://transmission.sourcearchive.com/documentation/1.75/event_8h_b652a2f82d23509713258a6e44697164.html#b652a2f82d23509713258a6e44697164

 int evbuffer_add   (   struct evbuffer *   ,
    const void *    ,
    size_t           
)           

Append data to the end of an evbuffer.

Parameters:

    buf     the event buffer to be appended to
    data    pointer to the beginning of the data buffer
    datlen  the number of bytes to be copied from the data buffer 

关于C & Libevent : add binary data to output buffer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8399682/

相关文章:

c - 2个数字的总和,输入错误

comparison - 字符缓冲区比较

node.js - 将 NodeJS 缓冲区转换为整数

Excel VBA 无法读取超过 40,000 个字符的 Web 源

c - 小于 0.(0 点)是什么意思?

c - Linux内核UDP接收时间戳

c - 多线程没有明显的性能提升

java - 从十六进制转换为二进制,反之亦然。艰难的道路

python - ARINC429 构词法

python re 模块替换文本文件中的二进制数据?