我正在构建一个客户端,可以从服务器和用户接收信息(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