使用 select() 的请求/回复服务器。无法写回客户端

request/reply server using select(). Can't write back to client

本文关键字:服务器 客户端 写回 回复 select 请求 使用      更新时间:2023-10-16

我从Beej指南中获得了所有这些代码,因此可以从那里看到所有接受。在Beej的代码中,他从客户端收到一条消息,然后将消息发送给所有其他客户端。这可以从这里的片段中看到:

                // handle data from a client
                if ((nbytes = recv(i, buf, sizeof buf, 0)) <= 0) {
                    // got error or connection closed by client
                    if (nbytes == 0) {
                    //handle error
                    }
                } 
                else {
                    // we got some data from a client
                    for(j = 0; j <= fdmax; j++) {
                        // send to everyone!
                        if (FD_ISSET(j, &master)) {
                            // except the listener and ourselves
                            if (j != listener && j != i) {
                                if (send(j, buf, nbytes, 0) == -1) {
                                    perror("send");
                                }
                            }
                        }
                    }
                }
            } // END handle data from client

我想将其调整到请求/回复功能中,而不是向所有客户端发送相同的消息,并将回复发送给我从。

的同一客户端发送。

这是我到目前为止所拥有的:

long length = 0;
string stringRead;
messagebroker broker;
read( i, &length, sizeof( length ) );
length = ntohl( length );
if(length > -1)
while ( 0 < length ) {
     char buffer[1024];
     int cread;
     cread = read( i, buffer, min( sizeof( buffer ), length ) );
     stringRead.append( buffer, cread );
     length -= cread;
 }
cout << "Got Message: " + stringRead << endl;
string response = broker.handleMessage(stringRead.c_str());
cout << "sending response" << response << endl;
//socket ready for writing
if (FD_ISSET(i, &master)) { //should i check to see if write_fds? I have this here
                                //simply because the guide has it, but i am suspicious
                                //it is there so we can not write to the master.
  length = htonl( response.length() );
  cout << "sent length" << endl;
  if(send( i, &length, sizeof(length) , 0) == 0){
     fprintf(stderr, "Error sending data %dn", errno);
     exit(3);
  }
  if(send( i, response.data(), response.length(),0 )== 0){
          fprintf(stderr, "Error sending data %dn", errno);
          exit(3);
      }
    }   //end if

我从服务器上的客户端接收所有数据。然后,我不确定问题是在服务器上写回数据还是从客户端读取数据。我认为它是从服务器写给客户端的。当我在评论中暗示时,我想我知道我在哪里出错了,但是我已经删除了此IF语句,但我仍然无法阅读客户端的任何内容。我一开始需要设置一个可写的标志吗?请让我知道您是否需要其他任何东西。抱歉,这个帖子很长。

只需写写即可。如果它返回-1/ewoldBlock,或一个表示未写入完整响应的值,则然后, ,将FD添加到WriteFDS中,并在FD变为可写时继续写入。通常,您没有任何写入FD,因为FD通常是可写的,也就是说,它们通常在插座发送缓冲区中有空间。