首页 > 代码库 > 消息队列实现实时通信

消息队列实现实时通信

此实例是一个简单的使用消息队列进行实时聊天的本机通信程序,,发送端每发送一个消息,会立即被接收读取,在没有消息在消息队列中时,将处于阻塞状态。

终端1运行接收端

#include <stdio.h>#include <string.h>#include <unistd.h>#include <stdlib.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>struct msgbuf{    int type;    char ptr[0];};int main(int argc, char *argv[]){    key_t key;    key=ftok(argv[1],100);    int msgid;    msgid=msgget(key,IPC_CREAT|0600);    pid_t pid;    pid=fork();    if(pid==0)    {        while(1)        {            printf("pls input msg to send:");            char buf[128];            fgets(buf,128,stdin);            struct msgbuf *ptr=malloc(sizeof(struct msgbuf)+strlen(buf)+1);            ptr->type=2;            memcpy(ptr->ptr,buf,strlen(buf)+1);            msgsnd(msgid,ptr,strlen(buf)+1,0);            free(ptr);        }    }    else    {        struct msgbuf        {            int type;            char ptr[1024];        };        while(1)        {            struct msgbuf mybuf;            msgrcv(msgid,&mybuf,1024,1,0);            printf("rcv msg:%s\n",mybuf.ptr);        }    }    return 0;}

终端2运行发送端

#include <stdio.h>#include <string.h>#include <unistd.h>#include <stdlib.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>struct msgbuf{    int type;    char ptr[0];};int main(int argc, char *argv[]){    key_t key;    key=ftok(argv[1],100);    int msgid;    msgid=msgget(key,IPC_CREAT|0600);    pid_t pid;    pid=fork();    if(pid==0)    {        while(1)        {            printf("pls input msg to send:");            char buf[128];            fgets(buf,128,stdin);            struct msgbuf *ptr=malloc(sizeof(struct msgbuf)+strlen(buf)+1);            ptr->type=1;            memcpy(ptr->ptr,buf,strlen(buf)+1);            msgsnd(msgid,ptr,strlen(buf)+1,0);            free(ptr);        }    }    else    {        struct msgbuf        {            int type;            char ptr[1024];        };        while(1)        {            struct msgbuf mybuf;            msgrcv(msgid,&mybuf,1024,2,0);            printf("rcv msg:%s\n",mybuf.ptr);        }    }    return 0;}