代码之家  ›  专栏  ›  技术社区  ›  user3751012

使用C在服务器端读取从客户端发送的文本文件

  •  1
  • user3751012  · 技术社区  · 10 年前

    我想从客户端发送一个文本文件,想在服务器端读取文本文件,并想在服务器终端屏幕上显示文本。我已经成功地为服务器和多个客户端编写了代码。我还从客户端向服务器端发送了一个文本文件。但现在我想知道如何修改文本文件并发送它,并在服务器端读取从客户端发送的文本文件。我的服务器和客户端代码如下:

    服务器和客户端代码:

    #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//myname//Documents//folder1//folder2//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 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;
                int fsize;
    
                pf = fopen(filename, "rb");
                if (pf == NULL)
                {
                    printf("File not found!\n");
                    return 1;
                }
                else
                {
                    printf("Found file %s\n", filename);
    
                    fseek(pf, 0, SEEK_END);
                    fsize = ftell(pf);
                    rewind(pf);
    
                    printf("File contains %ld bytes!\n", fsize);
                    printf("Sending the file now\n");
                }
    
                while (1)
                {
                    // Read data into buffer.  We may not have enough to fill up buffer, so we
                    // store how many bytes were actually read in bytes_read.
                    int bytes_read = fread(buffer, sizeof(buffer), 1, pf);
                    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, buffer, 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];
    
        //PROBLEM **read the text file sent from client side and display the text on screen**
        while( (read_size = recv(sock , client_message , sizeof(client_message) , 0)) > 0 )
        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;
    }
    
    1 回复  |  直到 10 年前
        1
  •  2
  •   Chandru Deborah    10 年前

    你在代码中犯了一些错误。

    int bytes_read = fread(buffer, sizeof(buffer), 1 ,pf);
    

    当您打印 bytes_read 值,则打印1有一个结果。如果您将其传递给next,则它将重复打印h。

    使用以下语句而不是fread:

    int bytes_read = fread(buffer, 1, sizeof(buffer), pf);
    

    此语句仅返回正确的读取值。

    while (bytes_read > 0)
    {
       int bytes_written = write(sock, buffer, bytes_read);
       if (bytes_written <= 0)
       {
            error("ERROR writing to socket\n");
       }
    }
    

    在这部分代码中,您的程序将读取的内容一次又一次写入套接字而不中断,因此服务器可以不中断地打印文本。

    所以在write()之后使用此语句 bytes_read=bytes_read-bytes_written; 如果读取缓冲区完全写入套接字,则会中断语句。

    还有一点是,当您尝试使用file时,总是尝试使用long数据类型,因为int的范围比long的范围小。

    更新:
    fread(buffer, 1, sizeof(buffer), pf); 试试看。它会奏效的。


    可以使用open()或fopen()。

    fd=open("filename",O_RDWR);
    

    fd-返回打开文件的描述符。
    O_RDWR-用于打开文件进行读写,必须包含fcntl.h。

    fp=fopen("filename","r+");
    

    fp-文件指针。
    rw-已打开文件进行读取和写入。

    文件内容:

    Chandru
    ttttt.
    

    更换后:

    Stackoverflowt.
    

    这里的内容很大,因此在另一行中覆盖内容。 为了避免这种情况,您需要将更改的内容写入另一个文件中。 在另一个文件中写入时,很容易将文本附加到行尾。