Search code examples
csocketsbuffer

append to buffer while reading from socket


Hi I am trying to implement TCP socket stream. I have a buffer of size 12, and I am reading into this buffer in a loop.

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?

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. Writing hello the first time and the digit 1 the second time.

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.

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.

reading buffer from socket


Solution

  • You should send new position of buffer into read function.

    rv = read(ctx.sockfd, buf + bytes_received, buf_size - bytes_recevied);