資源簡介
采用客戶-服務器結構,其中服務器實現各個用戶的登錄并存儲相關信息,客戶端通過服務器端獲取當前登錄用戶信息,然后各客戶進程通過消息隊列實現雙向通信。
Linux IPC通信利用消息隊列消息機制,多線程通信,字符串處理,鏈表操作,信號簡單處理。消息隊列是System V支持一種IPC機制,通過類似鏈表的操作向一個FIFO里通過msgsnd發送用戶自定義數據,進程可以通過msgrcv來接收指定類似mtype的數據,從而實現進程間通信。
在服務器端實現廣播功能,以及服務器退出以后通知;所有客戶端退出并刪除消息隊列功能;對所有客戶端的統計由鏈表實現
在客戶端實現:上線提醒,下線提醒,服務器斷線后子進程都退出。

代碼片段和文件信息
#include?
#include?
#include?
#include?
#include?
#include?
#include?
#include?
#include?
#include?
#include?“msg.h“
int?main()
{
key_t?key;
pid_t?pid;
int?msgid;
int?TYPE_ME; //由getpid()來指定唯一該進程才有的mtype
struct?msgbuf?msg;?
TYPE_ME?=?getpid(); //用自己的進程號作為自己接收消息的消息類型
//生成消息隊列的key
if((key?=?ftok(“./“‘s‘))==-1){
perror(“ftok?error.“);
exit(0);
}
//如果服務器已創建消息隊列才可以打開,客戶端無權創建
if((msgid?=?msgget(keyMSG_Q_PERM))==-1){
printf(“[server?maybe?not?on?line...]\n“);
exit(1);
}
//實現登錄操作
printf(“請輸入登錄用戶名:“);
fgets(msg.user_nameMSG_SIZEstdin);
msg.user_name[strlen(msg.user_name)-1]=‘\0‘;
msg.mtype?=?MSG_TO_SERVER;
msg.subtype?=?1;
msg.pid?=?getpid();
msgsnd(msgid&msgMSG_LEN0); //MSG_SIZE是消息正文大小
//客戶端雙進程實現讀寫操作
if((pid?=?fork())==-1){
perror(“fork?error.“);
exit(1);
}else?if(pid?==?0){ //子進程負責讀
while(1){
msgrcv(msgid&msgMSG_LENTYPE_ME0);
//判斷接收到的消息是否為quit
if(strncmp(msg.mtext“quit“4)?==?0){
printf(“[server?will?close?in?3?seconds...]\n“);
kill(TYPE_MESIGUSR1);?//若接收到服務端關閉,kill所有進程
exit(0);
}
//檢測用戶是否輸入exit退出操作?
if(strncmp(msg.mtext“exit“4)?==?0){
msg.subtype?=?3;
}
//寫成switch方便功能擴展
switch(msg.subtype){
case?1:
printf(“[%s?Login]\n“msg.user_name);
break;
case?2:
printf(“[%s]:?%s“msg.user_namemsg.mtext);
break;
case?3:
printf(“[%s?Logout]“msg.user_name);
break;
default?:
break;
}
}
}else{ //父進程用于發送消息
msg.mtype?=?MSG_TO_SERVER;
msg.subtype?=?2; //設為廣播模式
while(1){
printf(“[%s]:\n“msg.user_name);
fgets(msg.mtextMSG_SIZEstdin);
msgsnd(msgid&msgMSG_LEN0);
//當此進程輸入exit時,表示進程推出聊天
//由服務器通知其他進程,該進程已下線
if(strncmp(msg.mtext“exit“4)==0){
msg.subtype?=?3;
msgsnd(msgid&msgMSG_LEN0);
sleep(2);
kill(pidSIGKILL);
exit(0);
}
}
}
return?0;
}
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????目錄???????????0??2017-12-01?10:22??源代碼\
?????文件????????2355??2016-12-29?17:01??源代碼\client.c
?????文件?????????299??2016-12-28?08:54??源代碼\msg.h
?????文件??????????14??2016-12-29?17:22??源代碼\sensitive.txt
?????文件????????4648??2016-12-29?17:12??源代碼\server.c
?????文件??????267776??2017-12-01?10:28??多人聊天室.doc
- 上一篇:MFC 動態創建按鈕
- 下一篇:PCA融合算法C++代碼
評論
共有 條評論