0

以下のコードを使用して、1 つのテキスト ファイルをクライアント側からサーバー側に転送しています。テキストファイル内に何かを書いていますが、「r +」を使用しているため、ストリームがテキストの前に配置されています。しかし、サーバー側では、全文 (新しく追加されたテキストとファイルにあった以前のテキスト) が表示されません。サーバー側は、ファイル内に書き込まれたテキストのみを表示しています。理由はわかりません。私の質問は

  1. フルテキスト (新しいテキストを含むファイル内のすべてのテキスト) がサーバー側に表示されないのはなぜですか?
  2. 全文を表示するには?

私のサーバーとクライアントのコードは次のとおりです: (「This is my text」のみを表示します。しかし、以前にファイル input.txt に「This is my program, I want to display the text written here!」と書きました。 display "これは私のテキストです。これは私のプログラムです。ここに書かれたテキストを表示したいです!")

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdint.h>
#include <stdlib.h>
#include <pthread.h>
#define filename "//home//Documents//Example//input.txt"

#define MAX_CLIENTS 5


//the thread function
void *new_connection_handler(void *);

int main(int argc , char *argv[])
{

    //client variables
    int sock;  
    struct sockaddr_in server;
    char buffer[256], server_reply[2000];
    int len;
    
    //server variables
    int socket_desc , client_sock;  
    struct sockaddr_in client;
    socklen_t c = sizeof(client);
    

    //check if the command contain less than two arguments 
    if(argc != 2)
      {
          printf("use either: %s <server/client>\n", argv[0]);
      }
    
    // If the command contains minumum 2 arguments
     else{

    
    // If argv is client then execute the client code
     if(strcmp("client",argv[1]) == 0)
        {
/****************/// Client code here **********************************************************************
          //Create socket
                sock = socket(AF_INET , SOCK_STREAM , 0);
            if (sock == -1)
                {
                printf("Could not create socket");
                }
        puts("Socket created");

        server.sin_addr.s_addr = inet_addr("127.0.0.1");
        server.sin_family = AF_INET;
        server.sin_port = htons( 8888 );

        
        //Connect to remote server
        if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
           {
            perror("connect failed. Error");
            return 1;
           }

        puts("Connected\n");

        
        //keep communicating with server
        /* Time to send the file */

              /******************************************************/
        FILE *pf;
        long int fsize;
        //char str[] = "This is my text.\n";

        //pf = fopen(filename, "r+");
        //fwrite(str , 1 , sizeof(str) , pf );  
          int str=malloc(2000);// update
          strcpy(str,"This is my text.\n");// update
          pf = fopen(filename, "rb");//update
        
        
        if (pf == NULL) 
           {
                printf("File not found!\n");
                return 1;
           }
        else 
           {
                printf("Found file %s\n", filename);

                fseek(pf, 0, SEEK_CUR);
                fsize = ftell(pf);
                rewind(pf);

                printf("File contains %ld bytes!\n", fsize);
                printf("Sending the file now\n");
           }

        while (1) 
           {
                int bytes_read = fread(buffer, 1, sizeof(buffer), pf);
                strcat(str,buffer);// update
                bytes_read=strlen(str);    //update  
                if (bytes_read == 0) // We're done reading from the file
                break;

                if (bytes_read < 0) 
                   {
                    error("ERROR reading from file\n"); 
               }

                while (bytes_read > 0) 
                   {
                    int bytes_written = write(sock, str, bytes_read);// update
                    printf ("bytes_read value %ld\n",bytes_written);
                    bytes_read=bytes_read-bytes_written;
                    //printf ("bytes_read value1 %ld\n",bytes_read);
                    if (bytes_written <= 0) 
                       {
                            error("ERROR writing to socket\n");
                       }
       
                   }    
          }       


        printf("Done Sending the File!\n");
        printf("Now Closing Connection.\n");

        /*********************************************************************************/

        close(sock);

    }
        
    /****************/// Server code here **********************************************************************
        // If argv is server then execute the server code
    if(strcmp("server", argv[1]) == 0 )
        {
            //Create socket
            socket_desc = socket(AF_INET , SOCK_STREAM , 0);
            if (socket_desc == -1)
              {
                printf("Could not create socket");
              }

            //Prepare the sockaddr_in structure
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = INADDR_ANY;
            server.sin_port = htons( 8888 );
            bzero (&server.sin_zero, 8);

            //Bind
            if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
              {
                //print the error message
                perror("bind failed. Error");
                return 1;
              }

            //Listen
            listen(socket_desc , MAX_CLIENTS);

            //Accept and incoming connection
            printf("Waiting for incoming connections\n");

                c = sizeof(client);
            while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, &c)) )
            {
                printf("Connection accepted\n");
                pthread_t thread_id;

                if( pthread_create( &thread_id , NULL ,  new_connection_handler , (void*) (intptr_t)client_sock) < 0)
                  {
                    perror("could not create thread");
                    return 1;
                  }

                printf("Handler assigned\n");
             }


            if (client_sock < 0)
             {
                perror("accept failed");
                return 1;
             }
               } 
         }
    return 0;
}


void *new_connection_handler(void *socket_desc)
{
    //Get the socket descriptor
    int sock = (intptr_t)socket_desc;
    int read_size = 0;
    char client_message[2000];
    int len;
    
   

    
    //Receive a message from client
     while( (read_size = recv(sock , client_message , sizeof(client_message) , 0)) > 0 )
        printf ("Read size %d",read_size);
        printf("Read Text: %.*s", read_size, client_message);

    if(read_size == 0)
    {
        printf("Client disconnected\n");
        fflush(stdout);
    }
    else if(read_size == -1)
    {
        perror("recv failed");
    }
        
   
    return 0;
}
4

1 に答える 1

1

ファイルにfwrite()を使用してコンテンツを直接書き込むことはできません。既存のコンテンツを上書きします。

操作を分割します。

fread()を使用してファイルからコンテンツを読み取り、バッファに格納します。

次に、バッファーを別のバッファーと連結します。

char str[]="This is my text.\n";

上記の宣言は、別の文字列と連結すると、セグメンテーション違反につながる可能性があります。

その代わりに、 malloc()を使用して実行時にメモリを割り当てることができます。

str=malloc(2000);

割り当てられたメモリは、実行時にfree()関数を使用してクリアできます。

次に、strcpy()を使用して、テキストをバッファーにコピーします。メモリ割り当て後に直接割り当てることができます。

strcpy(str,"This is my text.\n");

これで、 strcat()を使用して、読み取ったバッファを str と連結できます。

strcat(str,buffer);

strlen()を使用して、連結された文字列の長さを見つける必要があります。

bytes_read=strlen(str);

strcat()、strcpy()、strlen() にアクセスするには、ヘッダー ファイルをインクルードする必要があります。string.h

str次のようにソケットに書き込みます。

write(sock, str, bytes_read);

ステップを使用すると、問題なく動作します。

アップデート:

int str=malloc(2000);

その使用の代わりに:

char *str=malloc(2000);

strcat(str,buffer);// update            
bytes_read=strlen(str);    //update

その2行の代わりに、次のようなstrcat関数で次の行を使用します

if(bytes_read != 0)
{ 
    strcat(str,buffer);// update            
    bytes_read=strlen(str);    //update
}

スレッド関数で、printf を次のように変更します。

printf("Read Text: %s", client_message); 

上記の変更を行った場合、プログラムは期待どおりに動作します。

于 2014-07-15T12:21:12.520 に答える