嗨,我正在尝试实现TCP套接字流。我有一个大小为12的缓冲区,我在循环中读入这个缓冲区。
我希望read操作在每次read调用时都会添加到缓冲区中,直到缓冲区已满为止,但是相反,它会从缓冲区的开头开始,在每次迭代时覆盖缓冲区中已经存在的内容。
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);
}
}
当我连接telnet并按enter分隔写两次时,我得到这个输出。写作
hello
第一次和数字
1
第二次。
reading from socket: 5
bytes_recevied: 7
buf: hello
bytes_recevied: 10
buf: 1
lo
hello1
而不是
1\rlo
.
reading buffer from socket