我正在构建一个可以从服务器和用户(stdin
)接收信息的客户端,所以我使用 select 来监控两者。发生的情况是键盘输入被监控,我向客户端发送消息并返回,没问题。但是当服务器发送消息时没有任何反应,我不知道为什么。是否使用select()
正确的方法来做到这一点?
这是我的代码:
void readSocket(fd_set tempfd) {
const char * tweet, * inMessage;
if (FD_ISSET(srverfd,&tempfd)) {
inMessage = getMessage();
printSystemMessages(inMessage);
}
if (FD_ISSET(STDIN_FILENO,&tempfd)) {
tweet = getUserTweet();
sendMessage(tweet);
inMessage = getMessage();
if (strcmp(inMessage,OK) != 0) {
printSystemMessages(inMessage);
}
if (strcmp(inMessage,EXIT) == 0) {
return;
}
}
return;
}
int main (int argc, char *argv[] ){
int value;
bool clientON = false;
fd_set tempfd;
if(establishConnection(argv[2],argv[3])){
cerr << "usage: failed to make connection" << endl << "exiting..." << endl;
exit(EXIT_FAILURE);
}
cout << "Connected successfully" << endl;
sendMessage("CONNECT "+clientName); //Connect
if(strcmp(getMessage(),OK) == 0){
build_select_list();
printSystemMessages("Welcome!");
clientON = true;
cout<< man <<endl;
}
while(clientON){
tempfd = inputFdSet;
printTweetFormat("TweetMy:");
value = select(maxSock, &tempfd, NULL, NULL, NULL);
if (value < 0) {
perror("select");
exit(EXIT_FAILURE);
}
if (value == 0) {
continue;
}
else {
readSocket(tempfd);
}
}
close(srverfd);
return 0;
}