c - 为什么 Else if 当我有 "ADD_FILE "不工作?

标签 c sockets networking file-io client-server

因此,我想创建一个具有不同操作的客户端服务器程序,例如获取文件夹中所有文件的最后修改时间 (GET_ALL_INFO)、获取一个文件夹的最后修改时间 (GET_FILE_INFO)、从服务器中删除文件 (REMOVE_FILE) 以及服务器上的 ADD_FILE,但是我有一个问题,它的分支没有被选中,因为当我在客户端中键入 ADD_FILE nameOfFile 时,每次都会被选中。我使用套接字传输文件和所有信息。

在其他服务器中 if(strncmp("ADD_FILE "....) 没有被检查 :( 为什么?

非常感谢您的帮助!

这是我的服务器代码:

#include <stdio.h>
#include <string.h>    //strlen
#include <stdlib.h>    //strlen
#include <sys/socket.h>
#include <arpa/inet.h> //inet_addr
#include <unistd.h>    //write
#include <pthread.h> //for threading , link with lpthread
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>

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

struct dirent_t {
    ino_t d_ino; /* inode number */
    off_t d_off; /* offset to the next dirent */
    unsigned short d_reclen; /* length of this record */
    unsigned char d_type; /* type of file */
    char d_name[256]; /* filename */
};

int socket_desc , client_sock , c , *new_sock;
struct sockaddr_in server , client;

int main(int argc , char *argv[])
{
    //Create socket
    socket_desc = socket(AF_INET , SOCK_STREAM , 0);
    if (socket_desc == -1)
    {
        printf("Could not create socket");
    }
    puts("Socket created");

    //Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons( 8888 );

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

    //Listen
    listen(socket_desc , 3);

    //Accept and incoming connection
    puts("Waiting for incoming connections...");
    c = sizeof(struct sockaddr_in);


    //Accept and incoming connection
    puts("Waiting for incoming connections...");
    c = sizeof(struct sockaddr_in);

    while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) )
    {
        puts("Connection accepted");

        pthread_t sniffer_thread;
        new_sock = malloc(1);
        *new_sock = client_sock;

        if( pthread_create( &sniffer_thread , NULL ,  connection_handler , (void*) new_sock) < 0)
        {
            perror("could not create thread");
            return 1;
        }

        //Now join the thread , so that we dont terminate before the thread
        //pthread_join( sniffer_thread , NULL);
        puts("Handler assigned");
    }

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

    return 0;
}

/*
 * This will handle connection for each client
 * */
void *connection_handler(void *socket_desc)
{
    //Get the socket descriptor
    int sock = *(int*)socket_desc;
    int read_size;
    char client_message[2000], path[2000];
    int fd = 0, condfd = 0, b, tot;
    char buff[1024];

    //Receive a message from client
    while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 )
    {
        int i = 0, j =0;

        if(strncmp(client_message, "GET_ALL_INFO ", 12) == 0)
        {
            for(i = 13; i < strlen(client_message); i++){
                path[j] = client_message[i];
                j++;
            }

            struct dirent_t *entry;
            DIR *dir = opendir(path);
            if (dir == NULL) {
                return;
            }

            while ((entry = readdir(dir)) != NULL)
            {
                struct stat attrib;
                stat(entry->d_name, &attrib);
                char date[30];
                strftime(date, 30, "%d-%m-%y", localtime(&(attrib.st_ctime)));
                //Send the message back to client
                write(sock , entry->d_name, strlen(entry->d_name));
                write(sock, "\t\t\t", strlen("\t\t\t"));
                write(sock, "last modified: ", strlen( "last modified: "));
                write(sock, date, strlen(date));
                date[0] = 0;
                write(sock , "\n", strlen("\n"));
            }

            closedir(dir);

            bzero(client_message, strlen(client_message));
            bzero(path, strlen(path));

        }
        else if(strncmp(client_message, "GET_FILE_INFO ", 13) == 0)
        {
             for(i = 14; i < strlen(client_message); i++){
                path[j] = client_message[i];
                j++;
            }

            struct stat attrib;
            stat(path, &attrib);
            char date[30];
            strftime(date, 30, "%d-%m-%y", localtime(&(attrib.st_ctime)));
            //Send the message back to client
            write(sock , path, strlen(path));
            write(sock, "\t\t\t", strlen("\t\t\t"));
            write(sock, "last modified: ", strlen("last modified: "));
            write(sock, date, strlen(date));
            date[0] = 0;
            write(sock , "\n", strlen("\n"));

            bzero(client_message, strlen(client_message));
            bzero(path, strlen(path));
        }
        else if(strncmp(client_message, "REMOVE_FILE ", 11) == 0)
        {
            for(i = 12; i < strlen(client_message); i++){
                path[j] = client_message[i];
                j++;
            }

            int status;

            status = remove(path);

            if(status == 0)
            {
                write(sock, path, strlen(path));
                write(sock, " file deleted successfuly.", strlen(" file deleted successfuly."));
                bzero(client_message, strlen(client_message));
                bzero(path, strlen(path));
            }
            else
            {
                write(sock, "Unable to delete the file!", strlen("Unable to delete the file!"));
                bzero(client_message, strlen(client_message));
                bzero(path, strlen(path));
            }
        }
        else if(strncmp(client_message, "ADD_FILE ", 8) == 0)
        {
             for(i = 9; i < strlen(client_message); i++){
                path[j] = client_message[i];
                j++;
            }

            FILE* fp = fopen(path, "w");
            tot = 0;

            if(fp != NULL)
            {
                while( (b = recv(client_sock, buff, 1024, 0)) > 0)
                {
                    tot += b;
                    fwrite(buff, 1, b, fp);
                }

                printf("Recieved byte: %d\n", tot);

                if(b < 0)
                    perror("Receiving");

                fclose(fp);
                bzero(client_message, strlen(client_message));
                bzero(path, strlen(path));
            }
            else
                perror("File");
        }
        else
        {
            write(sock , client_message , strlen(client_message));
            bzero(client_message, strlen(client_message));
            bzero(path, strlen(path));
        }

    }


    if(read_size == 0)
    {
        puts("Client disconnected");
        fflush(stdout);
    }
    else if(read_size == -1)
    {
        perror("recv failed");
    }

    //Free the socket pointer
    free(socket_desc);

    return 0;
}

这是我的客户端代码:

#include <stdio.h> //printf
#include <string.h>    //strlen
#include <sys/socket.h>    //socket
#include <arpa/inet.h> //inet_addr

int main(int argc , char *argv[])
{
    int sock;
    int b;
    struct sockaddr_in server;
    char message[1000] , server_reply[2000];

    //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
    b = connect(sock , (struct sockaddr *)&server , sizeof(server));
    if(b == -1)
    {
        perror("connect failed. Error");
        return 1;
    }

    puts("Connected\n");

    char file_name[2000];
    char send_buffer[1024];
    int i = 0, j = 0;
    //keep communicating with server
    while(1)
    {
        puts("Enter message : ");
        gets(message);

        if(strncmp(message, "ADD_FILE ", 8) == 0)
        {
             for(i = 9; i < strlen(message); i++){
                file_name[j] = message[i];
                j++;
            }

            FILE *fp = fopen(file_name, "r");
            if(fp == NULL)
            {
                perror("File");
                return 2;
            }

            while((b = fread(send_buffer, 1, sizeof(send_buffer), fp)) > 0)
            {
                send(sock, send_buffer, strlen(send_buffer), 0);
            }
            fclose(fp);
        }
        //Send some data
        else if( send(sock , message , strlen(message), 0) < 0)
        {
            puts("Send failed");
            return 1;
        }

        //Receive a reply from the server
        if( recv(sock , server_reply , 2000 , 0) < 0)
        {
            puts("recv failed");
            break;
        }

        puts("Server reply :");
        puts(server_reply);
        bzero(server_reply, strlen(server_reply));
    }

    close(sock);
    return 0;
}

最佳答案

你问的问题是在客户端。在:

    if(strncmp(message, "ADD_FILE ", 8) == 0)
    {
        ...
    }
    else if ...

消息未发送,仅发送文件。因此服务器永远不会收到消息 "ADD_FILE"

这部分代码还有另外两个问题:

  • j 未重置为 0
  • file_name 未以 '\0' 终止。

关于c - 为什么 Else if 当我有 "ADD_FILE "不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43976892/

相关文章:

python - 使用 Python 让客户端套接字等待服务器套接字

c - 设置 SSL - 初始步骤

java - Java RMI 是否使用服务器资源?

字符字符串覆盖其他字符串

c - TCP connect() 总是通过

ios - Swift:解释 NSURLSession.sharedSession().dataTaskWithURL 的语法语法

java - (网络套接字)字节在发送队列中停留 15 分钟;为什么?

c - scanf()、sscanf() 或 fscanf() 中的 %[] 或 %[^] 说明符是否将输入存储在以 null 结尾的字符数组中?

c - 查找线程堆栈大小

c++ - 无法在 C、C++ 和 Obj-C 中编译并带有特定错误消息的代码