基于Linux网络聊天室的设计 联系客服

发布时间 : 星期六 文章基于Linux网络聊天室的设计更新完毕开始阅读8e4d1c6a1eb91a37f1115c10

《基于Linux网络聊天室的设计》 第9页 共21页

}

}

{

mes[nbytes]='\\0'; }

printf(\

pthread_exit(NULL);

int main(int argc, char *argv[]) {

int sockfd; char buffer[1024];

struct sockaddr_in server_addr; struct hostent *host; int portnumber,nbytes; char strhost[16]; char clientname[20]; char mes[1024];

int thr_id; /* thread ID for the newly created thread */ pthread_t p_thread; /* thread's structure */ if(argc!=1) { }

printf(\请输入服务器ip地址\\n\scanf(\

if((host=gethostbyname(strhost))==NULL) {

fprintf(stderr,\fprintf(stderr,\exit(1);

exit(1);

《基于Linux网络聊天室的设计》 第10页 共21页

}

/* 客户程序开始建立 sockfd 描述符 */ printf(\正在建立套接口...\\n\

if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1) { }

/* 客户程序填充服务端的资料 */

bzero(&server_addr,sizeof(server_addr)); //给server_addr清零 server_addr.sin_family=AF_INET; server_addr.sin_port=htons(PORT);

fprintf(stderr,\exit(1);

server_addr.sin_addr=*((struct in_addr *)host->h_addr);

printf(\套接口创建成功,正在链接服务器...\\n\/* 客户程序发起连接请求 */

if(connect(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr))==-1) { }

/* 连接成功了 */

printf(\链接服务器成功\\n欢迎来到聊天室\\n\printf(\请输入你的用户昵称\\n\

scanf(\ // 输入(sockfd,clientname,sizeof(clientname));

fprintf(stderr,\exit(1);

printf(\开始聊天吧(\\\断开连接)\\n\\n\

thr_id = pthread_create(&p_thread, NULL, recvfromserver, NULL);

《基于Linux网络聊天室的设计》 第11页 共21页

}

while(1) { }

/* 结束通讯 */ close(sockfd); exit(0);

memset(buffer,0,sizeof(buffer)); memset(mes,0,sizeof(mes)); scanf(\ strcat(mes,clientname); strcat(mes,\strcat(mes,buffer);

printf(\if((write(sockfd,mes,sizeof(mes)))==-1) { }

if(strcmp(buffer,\{ }

break;

fprintf(stderr,\exit(1);

/******* 服务器程序 (server.c) ************/

#include #include #include #include #include

《基于Linux网络聊天室的设计》 第12页 共21页

#include #include #include

#define MAXLINE 1000 //在一条消息中最大的输出字符数 #define LISTENQ 20 //最大监听队列 #define PORT 5000 //监听端口

#define MAXFD 20 //最大的在线用户数量 void *get_client(void *); int sockfd,i;

static int maxi=0;//maxi表示当前client数组中最大的用户的i值 static int client[MAXFD];

void recvandsend(void) //监听转发线程入口函数 {

int index=0; int nbytes=0; char buffer[1024]; int len; int outindex=0; while(1) {

printf(\if(nbytes>0) { if(maxi>0) {

memset(buffer,0,sizeof(buffer)); nbytes=0;

//index++;

nbytes=read(client[index++],buffer,sizeof(buffer));