title: Data exchange between Server and Client with Ring Buffer (Circular Buffer) in C
body: <p>I wrote client-server chat for multiple clients (multiplexing i/o with non-blocking sockets). </p>
  
  <p>Now I have fixed bufferSize (for example, length = 64).
  I want to make data exchange between client and server with Ring Buffer. I also wrote a few functions (buffer inisialisation, popFront and pushBack) to write into a buffer.</p>
  
  <p>How is it possible to realize this idea? For example, I suppose I need 2 structures: the first structure has bufferlength and pointer to data in the other buffer, the second buffer has data. But now I have no idea what I should do with it. Could you give me an advice and maybe show with code? Thanks.</p>
  
  <p>Here are my ringBuffer structures and function (I suppose the function bufferSize is wrong):</p>
  
  <pre><code>struct ringBuffer
  {
      int *bufferData;
      int head;
      int tail;
      int size;
  };
  
  void bufferFree(struct ringBuffer *buffer)
  {
      free(buffer-&gt;bufferData);
  }
  
  void bufferInitialization(struct ringBuffer *buffer, int size)
  {
      buffer-&gt;size = size;
      buffer-&gt;head = 0;
      buffer-&gt;tail = 0;
      buffer-&gt;bufferData = (int*)malloc(sizeof(int) * size);
  }
  
  int pushBack(struct ringBuffer *buffer, int data)
  {
      buffer-&gt;bufferData[buffer-&gt;tail++] = data;
      if (buffer-&gt;tail == buffer-&gt;size)
      {
          buffer-&gt;tail = 0;
      }
      return 0;
  }
  
  int popFront(struct ringBuffer *buffer)
  {
      if (buffer-&gt;head != buffer-&gt;tail)
      {
          buffer-&gt;head++;
          if (buffer-&gt;head == buffer-&gt;size)
          {
              buffer-&gt;head = 0;
          }
      }
      return 0;
  }
  
  int bufferSize(struct ringBuffer *buffer)
  {
      if (buffer-&gt;head &gt;= buffer-&gt;tail)
      {
          return (buffer-&gt;head - buffer-&gt;tail);
      }
      else
      {
          return buffer-&gt;size - ((buffer-&gt;size - buffer-&gt;tail) + buffer-&gt;head);
      }
      /*for (int i = buffer-&gt;head; buffer-&gt;head &lt; buffer-&gt;tail; i++)
      {
      printf("head[%d] and tail[%d] --&gt; bufferData = %d", buffer-&gt;head, buffer-&gt;tail, buffer-&gt;bufferData);
      }*/
      return 0;
  }
  </code></pre>