我正在構建一個客戶端,可以從服務器和用戶接收信息(stdin
),所以我使用select來監視兩者。會發生什麼是一個鍵盤輸入被監控,我發送消息給客戶端,並得到一個回來,沒有問題。但是當服務器發送消息時什麼也沒有發生,我不知道爲什麼。正在使用select()
這樣做的正確方法?C++:使用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;
}
可以參考http://beej.us/guide/bgnet/對於選擇使用。 – CuriousSid
你有2個以上的主要功能 - 你可以真正清理這件事,使事情更清晰,然後更有可能得到答案 – mathematician1975
@curiousbill - 我讀了幾次,找不到答案。 – yotamoo