消息队列应用
多用户本地聊天
- 支持多人同时聊天(3人以上、可以修改程序设置)
- 每个用户端进程以ID登录,ID作为服务端要发送的消息类型
- 服务端实现消息的广播转发功能
客户端
可以根据输入数字获取个人ID
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define handle_error(s) \
{perror(s);exit(-1);}
#define TO_SERVER_MSGTYPE 1000
struct msgbuf {
long mtype;
int client_id;
char mtext[80];
};
int main(int argc, char *argv[])
{
key_t key = 512;
int msg_id = msgget(key, IPC_CREAT | 0666);
struct msgbuf msg_snd, msg_rcv;
/* 输入用户ID */
printf("input guest ID:");
int client_id;
scanf("%d", &client_id);
printf("client_id: %d\n", client_id);
int ret_from_fork;
ret_from_fork = fork();
if(ret_from_fork == -1)
handle_error("fork")
else if (ret_from_fork