在linux中使用命名管道的简单客户端/服务器程序

时间:2014-10-08 18:54:30

标签: c++ linux client-server named-pipes

我正在尝试编写一个程序,它有两个独立的进程,通过命名管道进行通信。向服务器发送消息的客户端,以及需要将该消息广播到连接到它的所有客户端的服务器。到目前为止,我可以在两者之间建立联系,但无论我尝试过什么,我都无法获得多条消息。下面是我编写的代码,它允许连接和传输单个消息。

server.cpp:

#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>

#define FIFO_FILE_1  "/tmp/client_to_server_fifo"
#define FIFO_FILE_2  "/tmp/server_to_client_fifo"

int main()
{
    int client_to_server;
    int server_to_client;
    char buf[BUFSIZ];

    /* create the FIFO (named pipe) */
    mkfifo(FIFO_FILE_1, 0666);
    mkfifo(FIFO_FILE_2, 0666);

    printf("Server ON.\n");

    while (1)
    {
    /* open, read, and display the message from the FIFO */
        client_to_server = open(FIFO_FILE_1, O_RDONLY);
        server_to_client = open(FIFO_FILE_2, O_WRONLY);

        read(client_to_server, buf, BUFSIZ);

        if (strcmp("exit",buf)==0)
        {
            printf("Server OFF.\n");
            break;
        }

        else if (strcmp("",buf)!=0)
        {
            printf("Received: %s\n", buf);
            printf("Sending back...\n");
            write(server_to_client,buf,BUFSIZ);
        }

        /* clean buf from any data */
        memset(buf, 0, sizeof(buf));

        close(client_to_server);
        close(server_to_client);
    }

    close(client_to_server);
    close(server_to_client);

    unlink(FIFO_FILE_1);
   unlink(FIFO_FILE_2);
    return 0;
}

client.cpp:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <wait.h>
#include <string.h>

#define FIFO_FILE_1  "/tmp/client_to_server_fifo"
#define FIFO_FILE_2  "/tmp/server_to_client_fifo"

int main()
{
    system("clear");
    int client_to_server;
    int server_to_client;

    char str[140];

    printf("Input message to server: ");
    scanf("%139[^\r\n]", str);

    /* write str to the FIFO */
    client_to_server = open(FIFO_FILE_1, O_WRONLY);
    server_to_client = open(FIFO_FILE_2, O_RDONLY);

    if(write(client_to_server, str, sizeof(str)) < 0){
        perror("Write:");//print error
        exit(-1);
    }
    if(read(server_to_client,str,sizeof(str)) < 0){
        perror("Read:"); //error check
        exit(-1);
    }
    printf("\n...received from the server: %s\n\n\n",str);

    close(client_to_server);
    close(server_to_client);

   /* remove the FIFO */

   return 0;
}

1 个答案:

答案 0 :(得分:0)

接近(client_to_server); 关闭(server_to_client);

从while循环中删除这些行,因为当服务器第一次完成其工作时,它将关闭管道并且您无法继续进行管道操作。