當(dāng)前位置:首頁 > 芯聞號 > 充電吧
[導(dǎo)讀]? ? ? ? ? ? ? ? ? ? ? ? ? ? 基于linux下的聊天程序設(shè)計(jì)與實(shí)現(xiàn)一、 ?實(shí)現(xiàn)的內(nèi)容及要求:? ? ? 用C語言編程實(shí)現(xiàn)linux簡單的聊天室功能。? 用戶程序命名為clie

? ? ? ? ? ? ? ? ? ? ? ? ? ? 基于linux下的聊天程序設(shè)計(jì)與實(shí)現(xiàn)

一、 ?實(shí)現(xiàn)的內(nèi)容及要求:

? ? ? 用C語言編程實(shí)現(xiàn)linux簡單的聊天室功能。


? 用戶程序命名為client.c;服務(wù)器程序命名為server.c? 綁定端口等信息見實(shí)驗(yàn)方法內(nèi)容;? 要求client可以通過socket連接server? 在client,提示輸入服務(wù)器ip? 若連接server 的socket建立成功,返回提示信息? Client輸入的聊天內(nèi)容在client端(多個(gè)client端)和server端同時(shí)顯示;? 多個(gè)client可同時(shí)接入server,進(jìn)入聊天室,最多支持20個(gè)client;? Client端輸入quit退出連接,server端提示client退出。? 可選擇使用多線程實(shí)現(xiàn)多客戶端;? 其他細(xì)節(jié)見輸出結(jié)果;


??????

二、方法及內(nèi)容

1.?????需要的頭文件

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

?

2.?????主要的常量變量

客戶端:

#define TRUE 1

#define PORT 5000

int quit=0;???? //quit表示是否用戶確定退出

?

服務(wù)器端:

#define MAXLINE 1000? //在一條消息中最大的輸出字符數(shù)

#define LISTENQ 20????????????? //最大監(jiān)聽隊(duì)列

#define PORT 5000?????????????? //監(jiān)聽端口

#define MAXFD 20??????????????? //最大的在線用戶數(shù)量

void *get_client(void *);????

int i,maxi=-1;//maxi表示當(dāng)前client數(shù)組中最大的用戶的i值

int client[MAXFD];


3.主要模塊

客戶端:

intmain(void)

void*get_server(void* sockfd)??

//get_server函數(shù),用于接受服務(wù)器轉(zhuǎn)發(fā)的消息


服務(wù)器端:

??? intmain()?

??? void*get_client(void *sockfd) //運(yùn)行g(shù)et_client函數(shù),處理用戶請求

?

三.完整代碼實(shí)現(xiàn)


注:參考socket編程

?

/******* 客戶端程序client.c ************/

#include

#include

#include

#include

#include

#include

#include

#include

?

?

#define TRUE 1

#define PORT 5000

?

static int sockfd;

void recvfromserver()??????? //接受服務(wù)器消息線程入口函數(shù)

{

?????? charmes[1024];

?????? int nbytes=0;

?

?????? while(1)

?????? {

????????????? memset(mes,0,sizeof(mes));

????????????? nbytes=read(sockfd,mes,sizeof(mes));

????????????? if(nbytes>0)

????????????? {

???????????????????? mes[nbytes]='