gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:31:44 24 4
gpt4 key购买 nike

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

服务器.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;
}

客户端.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;
}

最佳答案

关闭(客户端到服务器);关闭(服务器到客户端);

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

关于c++ - 在 Linux 中使用命名管道的简单客户端/服务器程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26264326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com