资源描述:
《Linux下多人聊天空间代码.doc》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、Linux下多人聊天空间代码在相同目录下新建文件wwb.h、wwb.c、room.c,把下面相应的代码拷进这两个文件里;再建一个recv.txt,该文件用于保存和显示聊天记录。在Linux中,使用下面命令编译:gcc-oroomroom.cwwb.c使用命令运行:./room使用命令查看聊天记录:tail-frecv.txt//wwb.h头文件intWriteLog(constchar*format,...);//写日志文件char*GetSysTime(char*time);//得到系统时间//wwb.
2、c代码#include#include#include#include#include#include#include#includeintWriteLog(constchar*format,...){FILE*fp;fp=fopen("recv.txt","a+");if(fp==NULL)return-1;va_listarg_ptr;va_sta
3、rt(arg_ptr,format);vfprintf(fp,format,arg_ptr);va_end(arg_ptr);fclose(fp);return0;}char*GetSysTime(char*out){time_ttimep;structtm*p;time(&timep);p=localtime(&timep);intyear=(1900+p->tm_year);intmonth=(1+p->tm_mon);intday=p->tm_mday;inthour=p->tm_hour;intm
4、inute=p->tm_min;intsecond=p->tm_sec;sprintf(out,"%d-",year);if(month<10)sprintf(out+5,"0%d-",month);elsesprintf(out+5,"%d-",month);if(day<10)sprintf(out+8,"0%d",day);elsesprintf(out+8,"%d",day);if(hour<10)sprintf(out+11,"0%d:",hour);elsesprintf(out+11,"%d
5、:",hour);if(minute<10)sprintf(out+14,"0%d:",minute);elsesprintf(out+14,"%d:",minute);if(second<10)sprintf(out+17,"0%d",second);elsesprintf(out+17,"%d",second);returnout;}/*intmain(){chartime[50];inti=10;char*s="hello";WriteLog("%s,%d,%s",GetSysTime(time
6、),i,s);}*///room.c主程序代码#include#include#include#include#include#include#include#include#include"wwb.h"#defineBUFSIZE255intmain(intargc,char*argv[]){if(argc!=2){pr
7、intf("Parameter(s):");exit(1);}char*username=argv[1];/*charusername[16]={0};do{printf("请输入你的用户名:");fgets(username,16,stdin);}while(!(strcmp(username,"")));*/in_port_tservPort=5000;char*bcIP="192.168.12.255";in_port_tbcPort=5000;pid_tpid;pid=
8、fork();if(pid>0)//ParentProcess{intsock1=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);if(sock1<0){printf("socket()failed");exit(1);}inton=1;setsockopt(sock1,SOL_SOCKET,SO_BROADCAST,&on,sizeof(on));structsockaddr_inbcAdd