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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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!
Btw you were too fast for stackoverflow, I must wait 5 minutes to approve your answer, thank!
@void &string[0] is only guaranteed to work since C++11 standard. See also this answer.
@zett42 And OP asked about a solution with unique_ptr, which is C++11 minimally as well.
Fair enough. I have suggested adding the appropriate tag.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.