用一个消息队列(System V)实现客户端-服务器端

1)类型字段可用于标识消息,从而允许多个进程在单个队列上复用消息。

2)类型字段可用作优先级字段。这允许接收者以不同于先进先出的某个顺序读出各个消息。使用管道或FIFO时,数据必须以写入的顺序读出。使用System V消息队列时,消息能够以任意顺序读出,只要跟消息类型关联的值一致就行。

#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<string.h>

#define KEY_MSG 0x101
#define MSGSIZE 64

typedef struct
{
  long mtype;
  char mtext[MSGSIZE];
}msgbuf;

#define LEN sizeof(msgbuf)-sizeof(long)

void main()
{
  int msgid;
  msgbuf buf1,buf2;
  msgid=msgget(KEY_MSG,IPC_CREAT|0666);
  while(1)
    {
      msgrcv(msgid,&buf1,LEN,1L,0);  //接收1的消息,返回类型为1L的第一个消息
      printf("Receive client1 message:%s\n",buf1.mtext);
      if(buf1.mtext[0]=='x' || buf1.mtext[0]=='X')
	{
	  strcpy(buf1.mtext,"x");
	  buf1.mtype=3L;
	  msgsnd(msgid,&buf1,LEN,0);
	  buf1.mtype=4L;
	  msgsnd(msgid,&buf1,LEN,0);
	  break;
	}
      buf1.mtype=4L;               //设置消息类型为4L
      msgsnd(msgid,&buf1,LEN,0);   //将从1接收到的消息发送给2
      msgrcv(msgid,&buf2,LEN,2L,0);  //接收2的消息
      printf("Receive client2 message:%s\n",buf2.mtext);
      if(buf2.mtext[0]=='x' || buf2.mtext[0]=='X')
	{
	  strcpy(buf2.mtext,"x");
	  buf2.mtype=3L;
	  msgsnd(msgid,&buf2,LEN,0);
	  buf2.mtype=4L;
	  msgsnd(msgid,&buf2,LEN,0);
	  break;
	}
      buf2.mtype=3L;               //设置消息类型为3L
      msgsnd(msgid,&buf2,LEN,0);   //将从2接收到的消息发送给1
    }
  sleep(1);
  msgctl(msgid,IPC_RMID,NULL);
}


//client1.c
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<string.h>

#define KEY_MSG 0x101
#define MSGSIZE 64

typedef struct
{
  long mtype;
  char mtext[MSGSIZE];
}msgbuf;

#define LEN sizeof(msgbuf)-sizeof(long)

void main()
{
  int msgid;
  msgbuf buf1,buf2;
  msgid=msgget(KEY_MSG,0666);
  while(1)
    {
      printf("Input the mag to client2:");
      gets(buf1.mtext);
      buf1.mtype=1L;
      msgsnd(msgid,&buf1,LEN,0);
      msgrcv(msgid,&buf2,LEN,3L,0);
      if(buf2.mtext[0]=='x'||buf2.mtext[0]=='X')
	{
	  printf("client1 will quit\n");
	  break;
	}
      else printf("Recevie from client2,message:%s\n",buf2.mtext);
    }
}

//client2.c
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<string.h>

#define KEY_MSG 0x101
#define MSGSIZE 64

typedef struct
{
  long mtype;
  char mtext[MSGSIZE];
}msgbuf;

#define LEN sizeof(msgbuf)-sizeof(long)

void main()
{
  int msgid;
  msgbuf buf1,buf2;
  msgid=msgget(KEY_MSG,0666);
  while(1)
    {
      msgrcv(msgid,&buf2,LEN,4L,0);
      if(buf2.mtext[0]=='x'||buf2.mtext[0]=='X')
	{
	  printf("client2 will quit!\n");
	  break;
	}
      else printf("Receive from client1,message:%s\n",buf2.mtext);
      sleep(1);
      printf("Input the msg to clinet1:");
      gets(buf1.mtext);
      buf1.mtype=2L;
      msgsnd(msgid,&buf1,LEN,0);
    }
}


其中的消息类型:

1L: client1------------------>server

2L: client2------------------>server

3L: server------------------>client1

4L: server------------------>client2

你可能感兴趣的:(用一个消息队列(System V)实现客户端-服务器端)