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

Sending large data package with TCP - winsock

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

Problem

A small struct is sent beforehand to the client that specifies package_size amount of data should be received which is what p->data_value_1 contains.

Server side:

void Server::sendDataSingleUser(char *data_in, int user, unsigned int package_size){
    package_size_sent_ = 0;
    FD_ZERO(&write_set_);
    FD_SET(sockets_[user], &write_set_);

    while(package_size_sent_  0){
            i_result_ = send(sockets_[num_clients_], data_in+package_size_sent_, package_size - package_size_sent_, 0);
            // Move buffer pointer
            if(i_result_ > 0){
                package_size_sent_ += i_result_;
            }

            // send error
            if(i_result_ == SOCKET_ERROR){
                // Handle the error
            }
        }
        // Socket still bussy
        else{
            // Disconnect the client
        }
    }
}


Client side:

*size_p = new char[(unsigned int)p->data_value_1];
int temp_count = 0, data_received, package_size = p->data_value_1;

while(temp_count  0){
        temp_count += data_received;
    }
}


What can be improved/what's incorrect?

Solution

In both read and write you should leave the loop after an error (unless you have explicitly tested and fixed the error).

while(totalRecieved  0)
    {
        totalRecieved += dataRecieved;
        continue;
    }
    if ((dataRecieved == -1) && (errno == EAGAIN || errno == EWOULDBLOCK))
    {
        // Simple error just try again.
        continue;
    }
    if (dataRecieved == -1 && errno == EINTR)
    {
        // An interrupt was received.
        // This is usually a signal by another thread to give up
        // but you can ignore it if you want.
        continue;
    }
    // Any other error is bad.
    // looping is just going to cause infinite loops.
    break;
}

if (totalRecieved < readSize)
{
    // BAD THINGS HAVE HAPPENED
}

Code Snippets

while(totalRecieved < readSize)
{
    dataRecieved = recv(socket, date + totalRecieved, readSize - totalRecieved);
    if (dataRecieved > 0)
    {
        totalRecieved += dataRecieved;
        continue;
    }
    if ((dataRecieved == -1) && (errno == EAGAIN || errno == EWOULDBLOCK))
    {
        // Simple error just try again.
        continue;
    }
    if (dataRecieved == -1 && errno == EINTR)
    {
        // An interrupt was received.
        // This is usually a signal by another thread to give up
        // but you can ignore it if you want.
        continue;
    }
    // Any other error is bad.
    // looping is just going to cause infinite loops.
    break;
}

if (totalRecieved < readSize)
{
    // BAD THINGS HAVE HAPPENED
}

Context

StackExchange Code Review Q#27213, answer score: 3

Revisions (0)

No revisions yet.