2014-10-08 95 views
0

我想編寫一個程序,它有兩個單獨的進程通過命名管道進行通信。向服務器發送消息的客戶端以及需要將該消息廣播給與其相連的所有客戶端的服務器。到目前爲止,我可以在兩者之間建立聯繫,但無論我嘗試過什麼,我都無法獲得多於一條消息。以下是我寫的代碼,它允許連接和傳輸單個消息。簡單的客戶端/服務器程序在Linux中使用命名管道

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

停止關閉循環中的FIFO。完成後請關閉它。 – Duck 2014-10-08 19:01:32

+1

你不檢查'open'和'close'的返回值!沒有!壞! – Gutblender 2014-10-08 19:01:35

回答

0

接近(client_to_server); close(server_to_client);

從while循環中刪除這些行,因爲當服務器第一次完成它的工作時,它將關閉管道並且無法在管道中進一步處理。

相關問題