c socket: recv and send data simultaneously

流过昼夜 提交于 2019-12-13 03:59:39

问题


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
  }
}

回答1:


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.



来源:https://stackoverflow.com/questions/14792741/c-socket-recv-and-send-data-simultaneously

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!