使用消息队列模拟服务器与客户端 客户端1 发送消息给服务端,发送的消息中携带了消息接收者的标识 客户端2 发送消息给服务端,发送的消息中携带了消息接收者的标识 服务端: 接收消息,根据消息中的消息接收者标识,转发给对应的消息接收者.
//服务端
server.c
#include "myhead.h"
typedef struct msgbuf
{
long mtype; // 消息的标识
char mtext[100]; // 消息的正文
}MSG;
int main(int argc, char const *argv[])
{
if (argc != 2)
{
printf("%s 消息标识n", argv[0]);
return -1;
}
int msgid, key;
key = ftok("./", 1);
if (key == -1)
{
perror("ftok() failed!");
return -1;
}
msgid = msgget(key, IPC_CREAT | 0666);
if (msgid == -1)
{
perror("msgget() failed!");
return -1;
}
MSG msg;
int mtype=atoi(argv[1]);
while(1)
{
//bzero(msg.mtext, sizeof(msg.mtext));
printf("输入要发送的消息Ser->Cli:");
scanf("%s",msg.mtext);
int ret = msgsnd(msgid, &msg, strlen(msg.mtext)+1, 0);
if (ret == -1)
{
perror("msgsnd() failed!");
return -1;
}
msgrcv(msgid,&msg,sizeof(msg), mtype,0);//接收标识为mtype的消息
printf("接收到的消息Cli->Ser: %sn",msg.mtext);
}
msgctl(msgid,IPC_RMID,NULL);
return 0;
}
//客服端
client.c
#include "myhead.h"
typedef struct msgbuf
{
long mtype; // 消息的标识
char mtext[100]; // 消息的正文
}MSG;
int main(int argc, char const *argv[])
{
if (argc != 2)
{
printf("%s 消息标识n", argv[0]);
return -1;
}
int msgid, key;
key = ftok("./", 1);
if (key == -1)
{
perror("ftok() failed!");
return -1;
}
msgid = msgget(key, IPC_CREAT | 0666);
if (msgid == -1)
{
perror("msgget() failed!");
return -1;
}
MSG msg;
int mtype=atoi(argv[1]);
while(1)
{
//bzero(msg.mtext, sizeof(msg.mtext));
msgrcv(msgid, &msg, sizeof(msg), mtype, 0);//接收标识为mtype的消息
printf("接收到的消息Ser->Cli:%sn",msg.mtext);
printf("输入要发送的消息Cli->Ser: ");
scanf("%s",msg.mtext);
int ret = msgsnd(msgid, &msg, strlen(msg.mtext)+1, 0);
if (ret == -1)
{
perror("msgsnd() failed!");
return -1;
}
printf("发送消息成功n");
}
return 0;
}



