Question

I use epoll in my server, and when I "simulate" load with sleep(2):

Client send: a
Client send: b
Client send: c

Server recv: abc

But, what I want:

Server recv: a
Server recv: b
Server recv: c

because I use weboscket frames, and I want handle there are one by one.

I need split buffer manually? Or is there more logical solution?

static const size_t RECV_BUFFER_SIZE = 1024;

size_t tcp_recv(int fd, char **buffer)
{
    size_t buffer_size = RECV_BUFFER_SIZE;
    size_t buffer_data_len = 0;

    *buffer = (char *)malloc(buffer_size);

    for (;;) {
        //sleep(2);
        ssize_t len;

        len = recv(fd, *buffer + buffer_data_len,
            buffer_size - buffer_data_len, 0);
        buffer_data_len += len;

        if (len == -1)
            break;

        if (len == buffer_size - buffer_data_len) {
            char *new_buffer;

            buffer_size *= 2;
            new_buffer = (char *)realloc(*buffer, buffer_size);
            if (new_buffer != NULL)
                *buffer = new_buffer;
        }
    }

    (*buffer)[buffer_data_len] = '\0';
    return buffer_data_len;
}
Was it helpful?

Solution

You need to implement your own protocol on top of the streaming TCP protocol.

Two possible approaches were:

  1. First send the length of the data to come in fixed length format, then send exactly this amount of bytes.
  2. Define a delimiter sequence used to terminate a data block having any length. For text data this could be a new-line sequence for example, that is \r\n as used by the http protocol.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top