0

私はノンブロッキングチャットサーバーを書いていますが、これまでのところサーバーは正常に動作していますが、部分的な送信が発生した場合に修正する方法がわかりません。send(int、char *、int); 関数は、成功した場合は常に0を返し、失敗した場合は-1を返します。私が読んだすべてのdoc/manページには、実際にネットワークバッファにフィードされたバイト数を返す必要があると書かれています。サーバーに送信し、問題なくデータを繰り返し受信できることを確認しました。

これは、送信を呼び出すために使用する関数です。私は両方とも最初に戻りデータをコンソールに出力しようとし、次に戻り戻り値で改行を試みました。デバッグ中。同じ結果、ReturnValueは常に0または-1です。

int Connection::Transmit(string MessageToSend)
{         
    // check for send attempts on a closed socket
    // return if it happens.
    if(this->Socket_Filedescriptor == -1)
        return -1;

    // Send a message to the client on the other end
    // note, the last parameter is a flag bit which 
    // is used for declaring out of bound data transmissions.
    ReturnValue  = send(Socket_Filedescriptor,
                         MessageToSend.c_str(),
                         MessageToSend.length(),
                         0); 

    return ReturnValue;        
}
4

1 に答える 1

0

ループで送信してみませんか?例えば:

int Connection::Transmit(string MessageToSend)
{         
    // check for send attempts on a closed socket
    // return if it happens.
    if(this->Socket_Filedescriptor == -1)
        return -1;

    int expected = MessageToSend.length();
    int sent     = 0;

    // Send a message to the client on the other end
    // note, the last parameter is a flag bit which 
    // is used for declaring out of bound data transmissions.
    while(sent < expected) {
      ReturnValue  = send(Socket_Filedescriptor,
                         MessageToSend.c_str() + sent, // Send from correct location
                         MessageToSend.length() - sent, // Update how much remains
                         0); 
      if(ReturnValue == -1)
        return -1; // Error occurred
      sent += ReturnValue;
    }

    return sent;        
}

このようにして、エラーが発生するか、すべてのデータが正常に送信されるまで、コードは継続的にすべてのデータを送信しようとします。

于 2013-01-02T00:17:30.270 に答える