0

我必须为 C++ 中的一个类实现一个 HTTP 服务器,但是在接受连接后,recv()只返回 -1。我怎样才能解决这个问题?我在下面发布了我的代码。

int main( int argc, char* argv[] )
{
  // Interpret the command line arguments
  unsigned short port = 8080;
  char* base_directory = NULL;
  base_directory = getcwd(base_directory, 100);

  if ( (argc != 1) && (argc != 3) && (argc != 5) ) {
    cerr << "Usage: " << argv[0];
    cerr << " -p <port number> -d <base directory>" << endl;
    return 1;
  }
  else {
    for (int i = 1; i < argc; ++i) {
      if (strcmp(argv[i], "-p") == 0)
        port = (unsigned short) atoi(argv[++i]);
      else if (strcmp(argv[i], "-d") == 0)
        base_directory = argv[++i];
    }
  }

  // Create TCP socket
  int tcp_sock = socket(AF_INET, SOCK_STREAM, 0);
  if (tcp_sock < 0) {
    cerr << "Unable to create TCP socket." << endl;
    return 2;
  }

  // Create server socket
  sockaddr_in server;
  server.sin_family = AF_INET;
  server.sin_port = htons( port );
  server.sin_addr.s_addr = INADDR_ANY;

  // Bind the socket
  if (bind(tcp_sock, (sockaddr*)&server, sizeof(server)) < 0) {
    cerr << "Unable to bind TCP socket." << endl;
    return 3;
  }

  // Listen for a connection request on TCP port
  listen(tcp_sock, 5);

  // Create HTTP_Request object and start a while loop of accepting connections
  char recv_buffer[3000];
  int bytes_recv = 0;
  int recv_len = 0;
  while (true) {
    int acc_tcp_sock = accept(tcp_sock, NULL, NULL);
    if (acc_tcp_sock == -1) {
      cerr << "Unable to open TCP connection with client." << endl;
      return 4;
    }
    do {
      recv_len = recv( tcp_sock, recv_buffer + bytes_recv,
        3000 - bytes_recv, 0 );
      bytes_recv += recv_len;
      cout << bytes_recv << endl;
      break;
    } while (recv_len);
    bytes_recv = 0;
    HTTP_Request* request = HTTP_Request::Parse(recv_buffer, 3000);
    cout << recv_buffer << endl;
  }

  return 0;
}
4

1 回答 1

2

你在错误的插座上recv'ing。您正在使用 tcp_sock(这是您的侦听套接字),而不是接受调用返回的套接字。将其更改为 acc_tcp_sock ,您应该一切顺利:

  recv_len = recv( acc_tcp_sock, recv_buffer + bytes_recv,
    3000 - bytes_recv, 0 );
于 2009-11-24T03:37:15.943 回答