I am writing a socket server in C++ and need to wrapper the read function, from an std::string
buffer. As you can see in the below code for reading a single byte (ClientConnection.readByte
), it uses a char
to store the value, delete it, then return the char
. However I also want to implement a readEverything (ClientConnection.readEverything
) function, which should return the entire buffer.
Right now, I just copy the buffer, but this doesn't seem memory efficient. This would be easy if I could return
before readBuffer.erase()
, but that can't work. Is there an efficient workaround, or do I just have to use my original method?
class ClientConnection{
private:
int connfd;
std::string writeBuffer;
std::string readBuffer;
struct sockaddr *address;
public:
ClientConnection(int fd){
connfd = fd;
}
bool available(){
char toReturn;
recv(connfd, &toReturn, 1, MSG_PEEK);
return toReturn!=-1;
}
char readByte(){
char thingy = readBuffer[0];
readBuffer.erase(0, 1);
return thingy;
}
std::string readEverything(){
std::string readBufferCopy = readBuffer;
readBuffer.erase();
return readBufferCopy;
}
void writeByte(char byte){
writeBuffer += byte;
}
void polleverything(){
write(connfd, writeBuffer.c_str(), writeBuffer.length());
char readBuffer[READOUTBUFFERSIZE];
while (recv(connfd, &toReturn, READOUTBUFFERSIZE, 0) == READOUTBUFFERSIZE){
std::cout << "HELLO";
};
}
};
The ClientConnection
class is supposed to be passed file descriptors and otherwise used by a server class, which for the sake of easy-reading I omitted from this snippet.
Thanks in advance!