I’m experimenting with select and have a simple app that writes, whatever the user entered in the command line, to a server. The server then echoes it back. I’m using the select function to listen on the connected socket and stdin.
Client code:
const int BUFFER_SIZE = 1024;
char *readArr = new char[BUFFER_SIZE];
fd_set rset;
ssize_t n;
string input;
FD_ZERO(&rset);
while(true){
FD_SET(socketFD[0], &rset);
FD_SET(0, &rset);
maxfpd1 = max(socketFD[0], 0) + 1;
select(maxfpd1, &rset, NULL, NULL, NULL);
if(FD_ISSET(0, &rset)){
cin>>input;
write(socketFD[0], input.c_str(), input.size());
cout<<"\nSocket write!\n";
}
if(FD_ISSET(socketFD[0], &rset)){
n = read(socketFD[0], readArr, BUFFER_SIZE-1);
readArr[n] = '\0';
cout<<"\nSocket read!\n";
cout<<readArr;
}
}
Now, if I type “Hello!” in the command line and hit enter, I get this output:
Hello! //User input
Socket write!//Client output
Socket read!//Client output
If I hit enter again, “Hello!” is printed. Why do I need to hit enter twice?
I can see from the server output that after the first enter the message is sent correctly to the server, and then back.
cin>>inputdoes not read the newline from the end of the line, andcout<<readArrdoes not write a newline. If you usecout<<readArr<<endlit will write a newline after the string and flush the output buffer. If you don’t want a newline after your string you can useflushinstead ofendlto only flush the output buffer. You could also changecoutto unbuffered if you don’t want it to buffer your output at all.