int getty_chat(char *scrstr, int timeout, int debug) { int r = -1; chat_alarm = timeout ? timeout : CHAT_DEFAULT_TIMEOUT; chat_debug = debug; if (scrstr != NULL) { char **script; if (chat_debug & CHATDEBUG_MISC) syslog(LOG_DEBUG, "getty_chat script='%s'", scrstr); if ((script = read_chat(&scrstr)) != NULL) { int i = r = 0; int off = 0; sig_t old_alarm; /* * We need to be in raw mode for all this * Rely on caller... */ old_alarm = signal(SIGALRM, chat_alrm); chat_unalarm(); /* Force blocking mode at start */ /* * This is the send/expect loop */ while (r == 0 && script[i] != NULL) if ((r = chat_expect(script[i++])) == 0 && script[i] != NULL) r = chat_send(script[i++]); signal(SIGALRM, old_alarm); free(script); free(scrstr); /* * Ensure stdin is in blocking mode */ ioctl(STDIN_FILENO, FIONBIO, &off); } if (chat_debug & CHATDEBUG_MISC) syslog(LOG_DEBUG, "getty_chat %s", result(r)); } return r; }
int main(int argc,char *argv[]) { struct data_bag bag; struct sockaddr_in client_addr,serv_addr; int sock_fd; char name[6]; char buf[MAX_CHAT]; int i; pthread_t thid; if((sock_fd=socket(AF_INET,SOCK_STREAM,0))<0) myerr("socket",__LINE__); memset(&serv_addr,0,sizeof(struct sockaddr_in)); serv_addr.sin_family=AF_INET; serv_addr.sin_port=htons(4507); if(inet_aton(argv[1],&serv_addr.sin_addr)<0) myerr("inet_aton",__LINE__); if(connect(sock_fd,(struct sockaddr *)&serv_addr,sizeof(struct sockaddr_in))<0) myerr("connect",__LINE__); time_get(); printf("已链接上服务器。。。\n"); // printf("请输入昵称:"); // fflush(stdin); // scanf("%s",bag.name); // getchar(); bag=screen(sock_fd); sleep(1); printf("登陆成功,开始聊天!\n"); printf("tips:默认进入群聊模式,私聊输入“-昵称:内容”\n"); printf("输入“lc”可查看该用户的私聊聊天记录\n"); printf("输入“l”可查看群聊聊天记录"); printf("输入“lo”可查看当前在线用户列表\n"); printf("输入“exit”可退出客户端\n"); if(pthread_create(&thid,NULL,(void *)rec,(void *)&sock_fd)!=0) myerr("pthread_create",__LINE__); while(1) { fflush(stdin); scanf("%s",bag.buf); if(bag.buf[0]=='-') { bag.flag=1; for(i=0;i<100;i++) if(bag.buf[i]==':') break; if(i!=100) send(sock_fd,(void *)&bag,sizeof(bag),0); else printf("输入不符合规范\n"); } else if(strcmp(bag.buf,"lc")==0) { read_chat(bag); } else if(strcmp(bag.buf,"l")==0) { system("cat group_chat"); } else if(strcmp(bag.buf,"lo")==0) { bag.flag=4; send(sock_fd,(void *)&bag,sizeof(bag),0); sleep(1); } else if(strcmp(bag.buf,"exit")==0) { printf("已成功退出聊天!\n"); exit(0); } else if((strcmp(bag.buf,"\0")!=0)&&(strlen(bag.buf)<=MAX_CHAT)) { bag.flag=0; send(sock_fd,(void *)&bag,sizeof(bag),0); write_chat1(bag); } else if(strlen(bag.buf)>MAX_CHAT) printf("字数过长,请分次输入!\n"); else printf("不能输入空消息\n"); } return 0; }