Carlj901
Carlj901

Reputation: 1411

Select on socket and stdin

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.

Upvotes: 0

Views: 2069

Answers (2)

Ross Smith
Ross Smith

Reputation: 3765

Your cin>>input doesn't read a whole line, only one word. It won't read the line feed, and if you type two words it won't read the second one. You should probably use getline(cin,input) instead, which reads the whole line and puts in in input (without the line feed, which is discarded).

Upvotes: 0

mark4o
mark4o

Reputation: 60863

cin>>input does not read the newline from the end of the line, and cout<<readArr does not write a newline. If you use cout<<readArr<<endl it will write a newline after the string and flush the output buffer. If you don't want a newline after your string you can use flush instead of endl to only flush the output buffer. You could also change cout to unbuffered if you don't want it to buffer your output at all.

Upvotes: 1

Related Questions