c socket: recv and send data simultaneously

2019-09-14 20:58发布

I'm having issues with my client side implementation of client server chat program where multiple clients connect. The issue is that i'm coming across is that how exactly should i be sending (chat message to another client) and receiving (chat message from another client) at the same time? What's happening is that i'm always sending data and never reading. Do i need to fork and have one read and the other send?

here is the relevant code

client side

while(1) {

  fd_set rfds, wfds;
  FD_ZERO(&rfds);
  FD_ZERO(&wfds);

  FD_SET(serverSocket, &rfds);
  FD_SET(serverSocket, &wfds);

  if(select(serverSocket+1, &rfds, &wfds, NULL, NULL) < 0) {
      perror("select");
      exit(-1);
  }

  if (FD_ISSET(serverSocket, &rfds)) {
     // we got data, read it
  }
  if (FD_ISSET(serverSocket, &wfds)) {
     printf(">");

     // read keyboard
     sendLen = 0;
     while ((cmd[sendLen] = getchar()) != '\n')
        sendLen++;
     cmd[sendLen] = '\0';

     // send the data
  }
}

标签: c sockets tcp fork
1条回答
狗以群分
2楼-- · 2019-09-14 22:04

You should put the file descriptor 0 (standard input) in the select as well, then read chars and buffer them, and when the socket is available for writing, copy the entire buffer on it. In this way you just block reading on the standard input all the time.

add

FD_SET(0, &rfds);

so select will return when user types something as well.

you must also use fcntl to set stdin as non-blocking. Then everytime select tells you there's data on stdin do something like that:

while(read(0,buffer+filled,1)>0) {}

Make sure to put another condition to exit the loop if the buffer is full.

then when you can write on the socket do a send, of the size of the amount of bytes you have in your buffer, check if all of it has been written, or move the leftovers bytes at the beginning of the buffer.

That while(getchar()) is blocking you preventing you from receving any messages.

查看更多
登录 后发表回答