单一消息队列完成客户-服务器进程间的双向通信

单一消息队列完成客户—服务器进程间的双向通信,客户端接收输入字符串,如接收到的是exit字符串,直接退出,否则传送接收字符串到服务器端,并等待服务器端回传消息。服务器端:接收客户端请求,接收后将接收到的字符串逆序后回传到对应客户端。

//服务器端:
#include<sys/msg.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<stdio.h>
#include<sys/errno.h>
#include<string.h>
extern int errno;
struct mymsgbuf1
{
	long mtype;
	char ctext[100];
};
struct mymsgbuf
{
	long mtype;
	pid_t pid;
	char ctext[100];
};
void main(){
	struct mymsgbuf buf;
	struct mymsgbuf1 buf1;
	int msgid,ret,i,len;
	if((msgid = msgget(0x1234,0666|IPC_CREAT))<0){
		fprintf(stderr,"openmsg%xfailed.\n",0x1234);
		return;
	}
	while(1)
	{
		memset(&buf,0,sizeof(buf));
		while((ret = msgrcv(msgid,&buf,sizeof(buf.ctext)+sizeof(buf.pid),1,0))<0)
		{
			if(errno == EINTR)continue;
			return;
		}
		fprintf(stderr,"Receivemessageform%d,content:%s\n",buf.pid,buf.ctext);
		memset(&buf1,0,sizeof(buf1));
		//strcpy(buf1.ctext,buf.ctext);
		len=strlen(buf.ctext)
		for(i = 0;i < len;i++)
		{
			buf1.ctext[len-1-i] = buf.ctext[i];
		}
		buf1.mtype = buf.pid;
		while((msgsnd(msgid,&buf1,strlen(buf1.ctext),0))<0)
		{
			if(errno == EINTR)continue;
			return;
		}
	}
}
//客户端:
#include<sys/msg.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<stdio.h>
#include<sys/errno.h>
#include<string.h>
extern int errno;
struct tmymsgbuf1
{
	longmtype;
	charctext[100];
};
struct mymsgbuf
{
	long mtype;
	pid_t pid;
	char ctext[100];
};
void main()
{
	struct mymsgbuf buf;
	struct mymsgbuf1 buf1;
	int msgid,ret;
	pid_t pid = getpid();
	if((msgid = msgget(0x1234,0666|IPC_CREAT))<0){
		fprintf(stderr,"openmsg%xfailed.\n",0x1234);
		return;
	}
	while(1)
	{
		memset(&buf,0,sizeof(buf));
		fgets(buf.ctext,sizeof(buf.ctext),stdin);
		if(!strcmp(buf.ctext,"exit"))
			break;
		buf.mtype = 1;
		buf.pid = pid;
		while((msgsnd(msgid,&buf,strlen(buf.ctext)+sizeof(buf.pid),0))<0)
		{
			if(errno == EINTR)continue;
			return;
		}
		memset(&buf1,0,sizeof(buf1));
		while((ret = msgrcv(msgid,&buf1,sizeof(buf1.ctext),pid,0))<0)
		{
			if(errno == EINTR)continue;
			return;
		}
		fprintf(stderr,"Receivemessageformservercontent:%s\n",buf1.ctext);
	}
}

在这里插入图片描述

一个服务器对应多个客户端,一个消息队列,客户端都将发送信息的类型设置为1,然后将自己的进程id放到数据部分,服务器接收所有客户端的请求,在返回给客户端信息的时候将类型设置为所接收的数据部分的进程id,客户端这边接收信息的函数里将接收类型设置为自己的进程id,就可以对应上了。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值