jeudi 27 avril 2017

Array of char using unique_ptr in this specific case

I am currently working on a little server using sockets in C++.

I have a function which sends string:

void SocketServer::SendData(int id_client, const std::string &str)
{
  int size = str.size();
  send(id_client, &size, 4, 0);
  send(id_client, str.c_str(), str.size(), 0);
}

First, I send 4 bytes which corresponds to the length of the string I want to send.

Then, I have a function which receives the string:

int SocketServer::ReceiveData(int id_client)
{
  char  buffer[1024]; // <<< this line, bad idea, I want to use unique_ptr
  int size = 0;
  int ret = 0;

  ret = recv(id_client, &size, 4, 0);  //<<< Now I know the length of the string I will get

  if (ret >= 0)
  {
    ret = recv(id_client, buffer, size, 0);
    if (ret >= 0)
    {
      buffer[ret] = '\0';
      std::cout << "Received: " << buffer << std::endl;
    }
  }
  return (ret);
}

I don't want to use a fixed buffer and I would like to use the unique_ptr (because it is a good way to respect the RAII)

How could I do that ?

Thank you very much

Aucun commentaire:

Enregistrer un commentaire