C中使用环形缓冲区(循环缓冲区)的服务器和客户机之间的数据交换

时间:2017-05-24 09:06:16

标签: c server client buffer circular-buffer

我为多个客户端编写了客户端 - 服务器聊天(使用非阻塞套接字复用i / o)。

现在我修复了bufferSize(例如,length = 64)。 我想用Ring Buffer在客户端和服务器之间进行数据交换。我还写了一些函数(缓冲区inisialisation,popFront和pushBack)来写入缓冲区。

如何实现这个想法?例如,我想我需要2个结构:第一个结构有缓冲区长度和指向另一个缓冲区中数据的指针,第二个缓冲区有数据。但是现在我不知道我应该怎么做。你能给我一个建议,也许可以用代码展示吗?感谢。

这是我的ringBuffer结构和函数(我想函数bufferSize是错误的):

struct ringBuffer
{
    int *bufferData;
    int head;
    int tail;
    int size;
};

void bufferFree(struct ringBuffer *buffer)
{
    free(buffer->bufferData);
}

void bufferInitialization(struct ringBuffer *buffer, int size)
{
    buffer->size = size;
    buffer->head = 0;
    buffer->tail = 0;
    buffer->bufferData = (int*)malloc(sizeof(int) * size);
}

int pushBack(struct ringBuffer *buffer, int data)
{
    buffer->bufferData[buffer->tail++] = data;
    if (buffer->tail == buffer->size)
    {
        buffer->tail = 0;
    }
    return 0;
}

int popFront(struct ringBuffer *buffer)
{
    if (buffer->head != buffer->tail)
    {
        buffer->head++;
        if (buffer->head == buffer->size)
        {
            buffer->head = 0;
        }
    }
    return 0;
}

int bufferSize(struct ringBuffer *buffer)
{
    if (buffer->head >= buffer->tail)
    {
        return (buffer->head - buffer->tail);
    }
    else
    {
        return buffer->size - ((buffer->size - buffer->tail) + buffer->head);
    }
    /*for (int i = buffer->head; buffer->head < buffer->tail; i++)
    {
    printf("head[%d] and tail[%d] --> bufferData = %d", buffer->head, buffer->tail, buffer->bufferData);
    }*/
    return 0;
}

1 个答案:

答案 0 :(得分:2)

Basically, you need two things:

  1. A shared ring of pointers between your clients and server.
  2. A shared pool of buffers between your clients and server.

There are a variety of flavors for the ring buffer: lockless, multi-consumer, multi-producer etc.

Have a look at DPDK's ring library as an example or lockless rings. Here is a detailed description of algorithms: http://dpdk.org/doc/guides/prog_guide/ring_lib.html

以下是代码: http://dpdk.org/browse/dpdk/tree/lib/librte_ring