用消息队列编写一个客户端服务器通信的程序

实验原理:

    本实验用消息队列设计一个简易的双人聊天程序(一个服务器,两个客户端)。消息队列重点在于消息类型的匹配,客户端和服务端的“通信协议”的设计。思想如下:

  服务器端:接受客户端发来的任何消息,并根据器消息类型,转发给对应的客户端。同时,检测是否有退出标记,有则给所有的客户端发送退出标记,等待1s后,确定客户端都退出,删除消息队列,释放空间,并退出。

  客户端:A和B。A给B发送信息,先发给服务器,由服务器根据自定义协议转发该消息给B。同时B也可以通过服务器给A发消息

  服务器:

#include
#include
#include
#include
#include

#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);
    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;
    msgsnd(msgid,&buf1,LEN,0);
    msgrcv(msgid,&buf2,LEN,2L,0);
    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;
    msgsnd(msgid,&buf2,LEN,0);
  }
    sleep(1);
    msgctl(msgid,IPC_RMID,NULL);
}


客户端1:

#include
#include
#include
#include
#include

#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;
        printf("Recevie from client2,message:%s\n",buf2.mtext);
     }
   }
}

客户端2:

#include
#include
#include
#include
#include

#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);
   }
}

你可能感兴趣的:(学习《unix环境高级编程》)