如果您无法下载资料,请参考说明:
1、部分资料下载需要金币,请确保您的账户上有足够的金币
2、已购买过的文档,再次下载不重复扣费
3、资料包下载后请先用软件解压,在使用对应软件打开
Linux网络编程:用C语言实现的聊天程序(同步通信)通过TCP协议,用C语言实现的同步聊天程序,注释写的比较详细,个人觉得对字符串处理比较充分,能够正常编译运行,拿出来和大家分享一下!1、客户端源代码:[cpp]HYPERLINK"http://blog.csdn.net/zx824/article/details/7752894"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/zx824/article/details/7752894"\o"copy"copyHYPERLINK"http://blog.csdn.net/zx824/article/details/7752894"\o"print"printHYPERLINK"http://blog.csdn.net/zx824/article/details/7752894"\o"?"?#include<stdio.h>#include<stdlib.h>#include<string.h>#include<errno.h>#include<sys/socket.h>#include<arpa/inet.h>#include<netinet/in.h>#include<sys/types.h>#include<unistd.h>#defineBUFLEN10intmain(intargc,char**argv){intsockfd;structsockaddr_ins_addr;socklen_tlen;unsignedintport;charbuf[BUFLEN];/*建立socket*/if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){perror("socket");exit(errno);}elseprintf("socketcreatesuccess!\n");/*设置服务器端口*/if(argv[2])port=atoi(argv[2]);elseport=4567;/*设置服务器ip*/bzero(&s_addr,sizeof(s_addr));s_addr.sin_family=AF_INET;s_addr.sin_port=htons(port);if(inet_aton(argv[1],(structin_addr*)&s_addr.sin_addr.s_addr)==0){perror(argv[1]);exit(errno);}/*开始连接服务器*/if(connect(sockfd,(structsockaddr*)&s_addr,sizeof(structsockaddr))==-1){perror("connect");exit(errno);}elseprintf("conncetsuccess!\n");while(1){/******接收消息*******/bzero(buf,BUFLEN);len=recv(sockfd,buf,BUFLEN,0);if(len>0)printf("服务器发来的消息是:%s,共有字节数是:%d\n",buf,len);else{if(len<0)printf("接受消息失败!\n");elseprintf("服务器退出了,聊天终止!\n");break;}_retry:/******发送消息*******/bzero(buf,BUFLEN);printf("请输入发送给对方的消息:");/*fgets函数:从流中读取BUFLEN-1个字符*/fgets(buf,BUFLEN,stdin);/*打印发送的消息*///fputs(buf,stdout);if(!strncasecmp(buf,"quit",4)){printf("client请求终止聊天!\n");break;}/*如果输入的字符串只有"\n",即回车,那么请重新输入*/if(!strncmp(buf,"\n",1)){printf("输入的字符只有回车,这个是不正确的!!!\n");goto_retry;}/*如果buf中含有'\n',那么要用strlen(buf)-1,去掉'\n'*/if(strchr(buf,'\n'))len=send(sockfd,buf,strlen(buf)-1,0);/*如果buf中没有'\n',则用buf的真正长度strlen(buf)*/elselen=send(sockfd,buf,strlen(buf