基于Linux的消息队列及多线程编程实现的聊天室(二)代码分析

本文通过分析Linux环境下的Makefile, msg.h, msg_svr.c和msg_client.c代码,详细讲解如何利用消息队列和多线程技术实现一个聊天室应用。" 79006807,7400295,C语言详解:深入理解一维数组,"['C语言', '数组', '编程基础']
摘要由CSDN通过智能技术生成

先将代码贴出来,然后慢慢再解释.

@Makefile

 

OBJS := server client
all: $(OBJS)

server: msg_svr.c msg.h 
	gcc -o $@ $^ -D_DEBUG

client: msg_client.c msg.h
	gcc -o $@ $^ -lpthread

clean:
	$(RM) $(OBJS)

 

 

 

@msg.h

 

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <signal.h>
#include <errno.h>
#include <time.h>
#include <sys/msg.h>

#define   MSG_FILE "/tmp/msg_server"    
#define   BUFFER 255    
#define   PERM S_IRUSR | S_IWUSR    

#define 	OK			1 
#define 	ERR			0

// msg type
#define   TYPE_SERVER		1000
#define   TYPE_SERVER_STR	"1000"

// msg target string
#define   SERVER_STR		"SERVER"
#define   TO_ALL_STR		"ALL"

// send cmd
// L, I, O is send to server
#define 	CMD_LIST		'L'
#define 	CMD_LOGIN		'I'
#define 	CMD_LOGOUT		'O'
#define 	CMD_TOALL 		'A'

// C, F send to others
#define 	CMD_CHAT		'C'
#define 	CMD_SEND_FILE	'F'

// CMD:FROM:TIME:DATA 
#define		DATA_LEN	4
#define		OFT_CMD		0
#define		OFT_FRM		1
#define		OFT_TIM		2
#define		OFT_DAT		3
#define		DATA_TOK	":"

// USR_ID:USR_NAME:TIME
#define		USER_DATA_LEN	3
#define		OFT_USR_ID		0
#define		OFT_USR_NM		1
#define		OFT_LOGIN_TM	2
#define		USER_DATA_TOK	"#"

// id admin
#define 	START_ID	1

//-------------------------------------+
// List operations
struct list_head {
	struct list_head *next;
};

// init a new list named name
#define LIST_INIT(name)	\
	struct list_head name = {NULL}

static inline int list_add(struct list_head * head, struct list_head* new){
	new->next = head->next;
	head->next = new;
}

static inline int list_delete(struct list_head * head, struct list_head* target){
	while(head){
		if(head->next == target){
			head->next = target->next;
			return 0;
		}
		head = head->next;
	}
	return -1;
}
//-------------------------------------+

// online status
enum status{ online, offline, invisible };

// available id 
int available_id = START_ID;

// user struct to save user informations
struct user{
	struct list_head list;
	int id;
	char name[32];
	enum status status;;
	long login_time;
};

// message struct
struct message
{    
	long mtype;
	char buffer[BUFFER+1];    
}msg_snd, msg_rcv;    

int msgid = 0;

// send a format message to client
// CMD:FROM:TIME:DATA 
int send_msg(long type, int cmd, in
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值