tags:

views:

51

answers:

1
void CApplication::SendData( const char pBuffer[] )
{
    if( pBuffer == NULL )
    {
        Log()->Write( ELogMessageType_ERROR, "Cannot send NULL message.");
        return;
    }
    // calculate the size of that data
    unsigned long messageSize = strlen( pBuffer );

    // fix our byte ordering
    messageSize = htonl( messageSize );

    if( isServer == true )
    {
        for( unsigned int i = ESocket_CLIENT0; i < ESocket_MAX; ++i )
        {
            // send the message size
            if( m_Socket[ i ] > 0 )
            {
                if( send( m_Socket[ i ], (char*)&messageSize, sizeof( messageSize ), 0 ) == SOCKET_ERROR )
                {
                    Log()->Write( ELogMessageType_ERROR, "[Application] Send error: %i to socket %i", WSAGetLastError(), m_Socket[ i ] );
                    continue;
                }

                // fix our message size back to host ordering
                messageSize = ntohl(messageSize);

                // send the actual message
                if( send( m_Socket[ i ], pBuffer, messageSize, 0 ) == SOCKET_ERROR )
                {
                    Log()->Write( ELogMessageType_ERROR, "[Application] Send error: %i to socket %i", WSAGetLastError(), m_Socket[ i ] );
                    continue;
                }

                Log()->Write( ELogMessageType_MESSAGE, "[Application] SEND: %s", pBuffer );
            }
        }
    }
+1  A: 

You're not handling the case where send() sends less data than you've asked it to. You need to loop if that is the case, until all data has gone out. You're also not handling errors in general, if a client has disconnected, send() might return -1 for instance.

The typical approach is something like::

for(size_t to_go = messageSize; to_go > 0;)
{
  int put = send(sock, buf, to_go);
  if(put < 0)
  {
    perror("Socket send() error");
    break;
  }
  buf += put;
  to_go -= put;
}

This attempts to send the entire remaining message, until all of it has been sent. You will of course need to adapt for your specific variable names, do better error-handling, and so on; please view the above as a sketch.

unwind
how do u think i should fix that?
thank you alot :)
@crsin: Feel free to accept the answer, if you feel it has helped you. :)
unwind