开发者

HTTP server, after a connection is accepted I get -1 returned from recv()

开发者 https://www.devze.com 2022-12-12 02:48 出处:网络
I have to implement an HTTP server for a class in C++, but after a connection is accepted, recv() just returns -1. How can I fix this? I posted my code below.

I have to implement an HTTP server for a class in C++, but after a connection is accepted, recv() just returns -1. How can I fix this? I posted my code below.

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


you are recv'ing on the wrong socket. You are using tcp_sock(which is your listening socket), not the socket returned by the accept call. Change it to acc_tcp_sock and you should be good to go:

  recv_len = recv( acc_tcp_sock, recv_buffer + bytes_recv,
    3000 - bytes_recv, 0 );
0

精彩评论

暂无评论...
验证码 换一张
取 消