无法接收客户输入

时间:2019-07-14 16:09:17

标签: c sockets tcpclient tcpserver

我编写了一个TCP服务器客户端代码,但无法正常运行,过程如下:

1-服务器向客户端发送菜单 2-客户回复,并带有与他要输入的文件关联的数字 3-服务器读取输入并将文件输出返回给客户端

我遇到的问题是我可以创建服务器套接字,绑定和监听,但是当涉及到客户端连接时,服务器端将定向到其他端口,结果是“无效输入。\ n”而没有任何客户端输入..

服务器

    while(1){

    if((clientfd = accept(serverfd, (struct sockaddr *) &client_addr, &addr_size)) < 0){

        printf("Connection failed.\n");
        exit(1);
    }

        printf("[SERVER]\tConnection accepted from %s: PID %d\n", inet_ntoa(client_addr.sin_addr), getpid());

        // send menu to user
        send(clientfd, MAINMENUSTR, 200, 0);

        if((childpid = fork()) == 0){
        close(clientfd);


    while(strcmp(buffer, "exit") != 0 || strcmp(buffer, "3") != 0){

        if(recv(clientfd, 1024, 0) < 0){

        }else{

        // if user enter menu
        if(strcmp(buffer, "menu") == 0){
        printf("[PID %d]\tRequested for main menu", getpid());
        appendLog(logPath, "Access to menu");
        send(clientfd, MAINMENUSTR, 200, 0);

        // if user enter exit
        }else if(strcmp(buffer, "exit") == 0 || strcmp(buffer, "3") == 0){

        printf("[SERVER]\tDisconnect from %s:  PID %d\n", inet_ntoa(client_addr.sin_addr), getpid());
        kill(getpid(), SIGQUIT);
        appendLog(logPath, "Exit. ");

        }else if(strcmp(buffer, "1") == 0){

        strcpy(buffer, "Accessing share folder.\n");
        printf("Accessing share folder.\n");

        }else{

        send(clientfd, "Invalid input try again.\n", sizeof(buffer), 0);
        printf("invalid input.\n");
        exit(1);
        }
        if(send(clientfd, buffer, sizeof(buffer), 0) < 0){

        perror("ERROR! unable to send messgae");
        memset(buffer, 0x0, 255);
        read(clientfd, buffer, 255);

        }
}
}// while
}// while
}

客户

while(1){

    // check receive from server
    if(recv(clientfd, buffer, 1024, 0) < 0){

    perror("error in receiving data.\n");
    close(clientfd);
    exit(1);

    }else{

    printf("%s", buffer);
    scanf("%s", &buffer[0]);
    send(clientfd, buffer, sizeof(buffer), 0);
    bzero(buffer, sizeof(buffer));
    }

    // if client enter 3, exit the program
    if(strcmp(buffer, "exit") == 0 || strcmp(buffer, "3") == 0){

    printf("Disconnected from server.\n");
    close(clientfd);
    exit(1);

    }


}// while

我的问题是,服务器-客户端之间如何进行发送和接收? 在while循环中调用send()和recv()函数的顺序重要吗?

0 个答案:

没有答案