2017-11-13 10 views
0

Cで単純なサーバークライアントプログラムを作成しようとしています。クライアントでサーバーからメッセージを受信しようとしましたが、メッセージのサイズはあらかじめ決められていません。したがって、どのくらいのバイトが入ってきているか確認したい、そして適切なサイズのmallocをチェックしたい。サーバーからのメッセージを正しく受信できないためにioctl()、read()、malloc()を使用する

私はioctlを使用しようとしましたが、私はあまりにも遅くしたい情報を得るようです。 これは私が持っているものです。

char *message_from_server; 
int length; 
while(1){ 
    ioctl(socket, FIONREAD, &length); 
    message_from_server = malloc(length); 
    read(socket, message_from_server, length); 
} 

私はそれを初めて使用するとき、lengthが0秒の時間であり、長さは、第1のメッセージと同じです。私が読んだ後に私がioctl(socket, FIONREAD, &length);という行を置くと、それは正しい量のスペースをmallocすることで私に問題を起こすかもしれません。これは私の問題を解決する有効な方法ですか?

私は問題を解決するためにreallocを使用することができると聞いていますが、私はそれをどのようにして問題を解決するのか苦労しています。それがより良い方法であれば、私はどんなヒントにも満足しています。

ありがとうございます!

+0

TCPのみでは、着信データのサイズがあらかじめ決められています。これは1バイト以上になります。 ioctlで 'peeking'することで1バイト以上のアプリケーションメッセージを実装しようとしている場合や、read()が常に1バイト以上の完全なメッセージでバッファをロードすると仮定すると、まもなく問題になります。 –

答えて

1

reallocを使用すると、メモリブロックのサイズを拡大し、その内容を保持することができます。

だから、あなたの場合:以前

  • を読んでてきたものを保存し、着信パケットの

    1. 読み取りサイズ
    2. 店舗のパケットに更新メモリブロックは、パケットに
    3. 後藤1を読んだり、 exit

    コードは次のようになります。

    /* memory to store message, initially, no memory */ 
    char *message_from_server = NULL; 
    /* size of memory */ 
    int total_length = 0; 
    
    /* sizeof incoming packet*/ 
    int packet_lentgh; 
    
    /* position to write in memory */ 
    int offset; 
    
    while(1){ 
        /* read size of incoming packet*/ 
        ioctl(socket, FIONREAD, &packet_lentgh); 
    
        if (0 != packet_lentgh) 
        { 
         /* something is ready to be read on socket */ 
    
         /* update memory size */ 
         total_length += packet_lentgh; 
    
         /* allocate much memory*/ 
         message_from_server = realloc(message_from_server, total_length); 
         if (NULL == message_from_server) 
         { 
          perror("realloc"); 
          abort(); 
         } 
    
         /* compute the position to write in memory */ 
         offset = total_length - packet_lentgh; 
    
         /* read the packet */ 
         read(socket, message_from_server + offset, packet_lentgh); 
        } 
        else 
        { 
         /* nothing to read 
          wait for packet or stop loop... */ 
        } 
    } 
    
  • +0

    ご迷惑をおかけして申し訳ありません。ありがとうございました! – tore

    関連する問題