void loop() { while(1) { bzero(writebuf,MAXDATESIZE); printf("客户端:"); scanf("%s",writebuf); len = strlen(writebuf); writebuf[len] = '\0'; if(strcmp(writebuf,"/add",4) == 0) { symbol = 2; bzero(writebuf,MAXDATESIZE); } else if(strcmp(writebuf,"/chat",5) == 0) { symbol = 3; bzero(writebuf,MAXDATESIZE); } else if((strcmp(writebuf,"Y") == 0) || (strcmp(writebuf,"y") == 0)) { symbol = 4; printf("Start chat:"); bzero(writebuf,MAXDATESIZE); } else if(strcmp(writebuf,"/groupchat",10) == 0) { symbol = 5; printf("Start groupchat:"); bzero(writebuf,MAXDATESIZE); } switch(symbol) { case 2: { addfriend(); break; } case 3: { sendchat(); break; } case 4: { startchat(); break; } case 5: { groupchat(); break; } } } }
void * handleClient(void *fd) { int cliFd = (int)fd; int recvRes, sendRes; char *username, *password; username = malloc(USERNAME_SIZE); password = malloc(USERNAME_SIZE); while(1) { if((recvRes = recv(cliFd, username, USERNAME_SIZE, 0)) <= 0 ) { perror("recv"); close(cliFd); pthread_exit(NULL); } if((recvRes = recv(cliFd, password, USERNAME_SIZE, 0)) <= 0 ) { perror("recv"); close(cliFd); pthread_exit(NULL); } int loginRes; if((loginRes = login(cliFd, username, password)) < 0) { char *msg = "Incorrect password\n"; if((sendRes = send(cliFd, msg, strlen(msg), 0)) < 0 ) { perror("send"); close(cliFd); pthread_exit(NULL); } } else { char *msg = "Login Success\n"; if((sendRes = send(cliFd, msg, strlen(msg), 0)) < 0 ) { perror("send"); close(cliFd); pthread_exit(NULL); } break; } } broadcast(username, "has connected!"); //inform everyone that the new client has connected showActiveUsers(cliFd, username); char *buf; buf = malloc(BUFFER_SIZE); while(1) { //keep listening for stuff that the client has to say recvRes=0; bzero(buf, BUFFER_SIZE); if((recvRes = recv(cliFd, buf, BUFFER_SIZE, 0)) < 0) { //if there's some error in receiving, remove client and close connection perror("recv"); broadcast(username, "has disconnected"); deactivate(cliFd); close(cliFd); pthread_exit(NULL); } else if(recvRes == 0) { //client disconnected. remove client and close connection broadcast(username, "has disconnected"); deactivate(cliFd); close(cliFd); pthread_exit(NULL); } int sendchatRes; if((sendchatRes = (sendchat(username, buf))) < 0) { if(sendchatRes == -1) strcpy(buf, "User is currently not online\n"); else strcpy(buf, "User doesnt exist\n"); if(send(cliFd, buf, strlen(buf), 0) < 0) { perror("send"); broadcast(username, "has disconnected"); deactivate(cliFd); close(cliFd); pthread_exit(NULL); } } } }