2

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

zett42
  • 25,437
  • 3
  • 35
  • 72
void
  • 407
  • 6
  • 18

1 Answers1

6

You could just use std::string instead:

std::string buffer;
int size = 0;                                                                                          
int ret = 0;                                                                                           

ret = recv(id_client, &size, 4, 0);
buffer.resize(size);

//later..
recv(id_client, &buffer[0], size, 0);             

buffer will now contain the received data and the correct size. It will also be destroyed for you because of RAII.

void
  • 407
  • 6
  • 18
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
  • Hello, thank you for your answer, it works like a charm! I didn't know that std::string was also considered as char*, thank you! – void Apr 27 '17 at 19:33
  • Btw you were too fast for stackoverflow, I must wait 5 minutes to approve your answer, thank! – void Apr 27 '17 at 19:34
  • 1
    @void `&string[0]` is [only guaranteed to work since C++11](http://stackoverflow.com/a/1986974/7571258) standard. See also [this answer](http://stackoverflow.com/a/33124544/7571258). – zett42 Apr 27 '17 at 20:01
  • 1
    @zett42 And OP asked about a solution with `unique_ptr`, which is C++11 minimally as well. – Hatted Rooster Apr 27 '17 at 20:05
  • Fair enough. I have suggested adding the appropriate tag. – zett42 Apr 27 '17 at 20:07
  • I'm compiling using -std=c++14, there is no problem for me, thank you very much – void Apr 27 '17 at 20:09