[英]append to buffer while reading from socket
Hi I am trying to implement TCP socket stream.您好我正在尝试实现 TCP 插座 stream。 I have a buffer of size 12, and I am reading into this buffer in a loop.
我有一个大小为 12 的缓冲区,我正在循环读取这个缓冲区。
I expected the read operation to add onto the buffer with each read call until the buffer is full, but instead, it starts from the beginning of the buffer, overwriting what is already in there on each iteration.我希望每次读取调用都会将读取操作添加到缓冲区中,直到缓冲区已满,但相反,它从缓冲区的开头开始,覆盖每次迭代中已经存在的内容。
How can I append to the buffer with each read, so that the previous bytes are preserved?如何在每次读取时将 append 写入缓冲区,以便保留以前的字节?
void *th_read(void *arg)
{
reader_arg_t *rArg = (reader_arg_t *)arg;
int buf_size = 12;
int bytes_recevied, rv;
char buf[buf_size];
while (1)
{
rv = 0;
bytes_recevied = rv;
memset(buf, 0, buf_size);
socket_context_t ctx;
tsq_dequeue(rArg->reader_queue, &ctx);
printf("reading from socket: %i\n", ctx.sockfd);
while (1)
{
rv = read(ctx.sockfd, buf, buf_size - bytes_recevied);
if (rv < 1)
break;
bytes_recevied += rv;
printf("bytes_recevied: %i\nbuf: %s\n", bytes_recevied, buf);
}
perror("read");
close(ctx.sockfd);
printf("%s\n", buf);
}
}
When I connect with telnet and write 2 times separates by pressing enter, I get this output.当我通过 telnet 连接并按 Enter 键写入 2 次分隔符时,我得到了这个 output。 Writing
hello
the first time and the digit 1
the second time.第一次写
hello
,第二次写数字1
。
reading from socket: 5
bytes_recevied: 7
buf: hello
bytes_recevied: 10
buf: 1
lo
I want the buffer to contain hello1
instead of 1\rlo
.我希望缓冲区包含
hello1
而不是1\rlo
。
I found a question that showed the zero byte thing but its not useful for my use case unless I would maybe use a second buffer and add on each read the stuff from the first buffer until the zero byte.我发现了一个显示零字节的问题,但它对我的用例没有用,除非我可能会使用第二个缓冲区并在每次读取时添加从第一个缓冲区读取的内容,直到零字节。
You should send new position of buffer into read function.您应该将缓冲区的新 position 发送到读取 function。
rv = read(ctx.sockfd, buf + bytes_received, buf_size - bytes_recevied);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.