栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

使用消息队列模拟服务器与客户端

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用消息队列模拟服务器与客户端

使用消息队列模拟服务器与客户端
客户端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;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/658162.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号