HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Optimize RecvData wrapper

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
wrapperoptimizerecvdata

Problem

How can I improve the string RecvData() function?

std::string Socket::RecvData() {
    std::string strBuffer;
    do{
        char buffer;
        int recvInt = recv(s_, &buffer, 1, 0);
        if (recvInt == INVALID_SOCKET)
        {
            return "";
        }
        if (recvInt == SOCKET_ERROR)
        {
            if (errno == EAGAIN) {
                return strBuffer;
            }
            else {
                // not connected anymore
                return "";
            }
        }

        strBuffer += buffer;
        if (buffer == '\n')  return strBuffer;
    } while (true);
}

Solution

recv() is a system call, which has relatively high overhead. You should avoid calling recv() just to read one byte at a time. Instead, read a reasonable sized buffer (something like the size of an IP packet). Your wrapper object should maintain a buffer of bytes that have been returned by a previous call to recv() but that have not yet been returned to the caller (bytes after a newline character).

In implementing such a buffered interface, you would be forced to use the return value of recv() correctly. recv() returns the number of bytes read, or -1 if an error occurred. The error code is stored in the errno global variable, not the return value of recv().

Context

StackExchange Code Review Q#47187, answer score: 6

Revisions (0)

No revisions yet.