如何使用两个发送功能发送GET请求?

时间:2019-05-28 09:49:43

标签: c++ sockets

此代码在一个发送功能的帮助下发送GET请求 但我想发送相同的GET请求,但将其分解并使用两个send函数发送。代码如下。

#include<iostream>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>//the new file.
#include<unistd.h>//for using the sleep function.
using namespace std;
int main(int argc,char* argv[]){
    //first we will do thigns with only one thread.
    char* address;
    address=argv[1];
    int network_socket;
    network_socket=socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in server_address;
    server_address.sin_family=AF_INET;
    server_address.sin_port=htons(80);
    //now we will set the ip address of the required field.
    inet_aton(address,(struct in_addr*)&server_address.sin_addr.s_addr);
    int connection_status=connect(network_socket,(struct sockaddr*)&server_address,sizeof(server_address));
    if(connection_status){
            cout<<"error in the setting up the connection"<<endl;
    }
    /*
    now since we want to mimic the http we will first send
    a request and then we will accept the reply.

    main question?
    -> how to construct a request ??:)
    */
    char request1[]="GET /index.html HTTP/1.1\r\n\r\n";
    char response[4096];
    send(network_socket,request1,sizeof(request1),0);
    recv(network_socket,&response,sizeof(response),0);
    cout<<response<<endl;
    close(network_socket);
    return 0;
    }
    /*
      but i want something like this
      char request1[]="GET /index.ht";
      char request2[]="ml HTTP/1.1\r\n\r\n";
      send(network_socket,request2,sizeof(request2),0);
      send(network_socket,request2,sizeof(request2),0);

      */
       //but doing this will make server give 400 error

1 个答案:

答案 0 :(得分:0)

您可以替换代码的以下部分:

char request1[]="GET /index.html HTTP/1.1\r\n\r\n";
send(network_socket,request1,sizeof(request1),0);

..例如,以这种方式:

char request1a[]="GET /index.html";
char request1b[]=" HTTP/1.1\r\n\r\n";
send(network_socket,request1a,sizeof(request1a)-1,0);
send(network_socket,request1b,sizeof(request1b),0);

请注意-1。这是必需的,因为您不想向服务器发送额外的“ \ 0”。使用strlen()是替代方法。

TCP是面向流的,因此多次发送不会在传输的数据上添加任何消息边界。它可能会生成更多的IP数据包,但不会破坏功能。

请记住为这些函数调用添加错误检查。