Winsock2.h не может отправлять http запросы - PullRequest
0 голосов
/ 23 мая 2018

Привет коллеги-программисты,

Я пытаюсь написать программу, которая позволит вам вводить то, что вы хотите, и программа отправит ваши данные на сервер.

На данный момент моя цельотправляет HTTP-запросы на веб-страницу.Подключается нормально.Но когда цикл while запускается, он сразу отправляет что-то через процедуру cin.getline, и я ничего не вводю.Я думал, что это странно, но, похоже, все равно работает.

Каждый раз, когда я отправляю что-то вроде: «GET / HTTP / 1.1 \ r \ n \ r \ n», он возвращает правильную вещь, но все, что угодноиначе я ввожу, как «OPTIONS» возвращает исходный код + «приложение заблокировано» (я в школе, так что это имеет смысл).

Итак, я подключился к VPN с защитной точкой доступа и протестировал приложение, но, к моему ужасу, когда я ввожу что-то для отправки, оно ничего не возвращает.

Я искал через переполнение стека и Google, но пока не смог найти ничего;вероятно, потому что я ищу неправильные решения проблемы.В любом случае, если у вас есть время, просканируйте код и отправьте помощь.Это может быть просто проблема VPN и школы, и я мог бы попробовать дома, если кажется, что код работает для вас, поэтому просто дайте мне знать.

СПЕЦИФИЧЕСКИЙ РЕЗУЛЬТАТ ПРОБЛЕМЫ: Когда я использую это вне школьной сетиничего не возвращается и цикл while не выполняется.Я могу подключиться, но программа, кажется, находится в бесконечном перерыве или что-то в этом роде.

    cout << "Connected to " << hostName << endl;



    while (true) {
        cout << ">";


        cin.getline(sendBuf, sizeof(sendBuf));
        string s(sendBuf);


        cout << s.c_str() << endl;


            send(connectSocket, s.c_str(), sizeof(s.c_str()), 0);

            int rec = recv(connectSocket, recvBuf, sizeof(recvBuf), 0);
            if (rec > 0) {
                cout << recvBuf << endl;
            }
            else if (rec <= 0) {
                cout << "nothing" << endl;
            }
        }

    system("pause");

}
system("pause");
}

1 Ответ

0 голосов
/ 23 мая 2018

моя цель - отправка HTTP-запросов на веб-страницу

Код, который вы показали, не пытается реализовать какое-либо подобие протокола HTTP , даже близко.

С одной стороны, если вы посмотрите на свой собственный пример более внимательно, вы увидите, что в запросе GET (кстати, отсутствует требуемый заголовок Host из-за использования HTTP 1.1).) содержит 2 переноса строк, но cin.getline() (почему не std::getline()?) читает только 1 строку за раз.Итак, вы читаете в одну строку, отправляете ее и ждете ответа, который не приходит, поскольку вы еще не закончили отправку полного запроса.Это объясняет, почему ваш while цикл зависает.

Если вы хотите, чтобы пользователь ввел полный HTTP-запрос, а затем отправили его как есть, вы должны прочитать ВЕСЬ запрос от пользователяи затем отправьте его полностью на сервер, прежде чем вы сможете попытаться получить ответ сервера.Это означает, что вам нужно обрабатывать разрывы строк между отдельными заголовками сообщений, обрабатывать завершающий разрыв строк, который отделяет заголовки сообщений от тела сообщения, и определять конец данных тела.

Я бы предложил не полагаться напользователь вводит полный HTTP-запрос как есть.Я предлагаю вам запросить у пользователя соответствующие фрагменты и позволить пользователю вводить обычный текст, а затем ваш код может отформатировать этот текст в нужный HTTP-запрос по мере необходимости.

Когда вы читаете ответ сервера, вы можете 'т просто слепо читать произвольные порции данных.Вы должны обработать то, что прочитали, согласно правилам протокола HTTP.Это особенно важно для определения того, когда вы достигли конца ответа и должны прекратить чтение.Об окончании ответа может быть сообщено одним из множества различных способов, как описано в RFC 2616, Раздел 4.4 Длина сообщения .

Вы также допускаете некоторые распространенные ошибки новичка в своей обработке TCP вгенеральный.TCP является потоковым транспортом, вы не учитываете, что send() и recv() могут отправлять / получать меньше байтов, чем запрошено.Или что recv() не возвращает данные с нулевым символом в конце.

С учетом сказанного попробуйте что-то вроде этого:

void sendAll(SOCKET sckt, const void *buf, int buflen)
{
    // send all bytes until buflen has been sent,
    // or an error occurs...

    const char *pbuf = static_cast<const char*>(buf);

    while (buflen > 0)
    {
        int numSent = send(sckt, pbuf, buflen, 0);
        if (numSent < 0) {
            std::ostringstream errMsg;
            errMsg << "Error sending to socket: " << WSAGetLastError();
            throw std::runtime_error(errMsg.str());
        }
        pbuf += numSent;
        buflen -= numSent;
    }
}

int readSome(SOCKET sckt, void *buf, int buflen)
{
    // read as many bytes as possible until buflen has been received,
    // the socket is disconnected, or an error occurs...

    char *pbuf = static_cast<char*>(buf);
    int total = 0;

    while (buflen > 0)
    {
        int numRecvd = recv(sckt, pbuf, buflen, 0);
        if (numRecvd < 0) {
            std::ostringstream errMsg;
            errMsg << "Error receiving from socket: " << WSAGetLastError();
            throw std::runtime_error(errMsg.str());
        }
        if (numRecvd == 0) break;
        pbuf += numRecvd;
        buflen -= numRecvd;
        total += numRecvd;
    }

    return total;
}

void readAll(SOCKET sckt, void *buf, int buflen)
{
    // read all bytes until buflen has been received,
    // or an error occurs...

    if (readSome(sckt, buf, buflen) != buflen)
        throw std::runtime_error("Socket disconnected unexpectedly");
}

std::string readLine(SOCKET sckt)
{
    // read a line of characters until a line break is received...

    std::string line;
    char c;

    do
    {
        readAll(sckt, &c, 1);
        if (c == '\r')
        {
            readAll(sckt, &c, 1);
            if (c == '\n') break;
            line.push_back('\r');
        }
        else if (c == '\n') {
            break;
        }
        line.push_back(c);
    }
    while (true);

    return line;
}

...

inline void ltrim(std::string &s) {
    // erase whitespace on the left side...
    s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
        return !std::isspace(ch);
    }));
}

inline void rtrim(std::string &s) {
    // erase whitespace on the right side...
    s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) {
        return !std::isspace(ch);
    }).base(), s.end());
}

inline void trim(std::string &s) {
    // erase whitespace on both sides...
    ltrim(s);
    rtrim(s);
}

inline void upperCase(std::string &s)
{
    // translate all characters to upper-case...
    std::transform(s.begin(), s.end(), s.begin(), ::toupper);
}

...

std::string makeRequest(const std::string &host, const std::string &method, const std::string &resource, const std::vector<std::string> &extraHeaders, const void *body, int bodyLength)
{
    std::ostringstream oss;
    oss << method << " " << resource << " HTTP/1.1\r\n";
    oss << "Host: " << host << "\r\n";
    oss << "Content-Length: " << bodyLength << "\r\n";
    for(auto &hdr : extraHeaders)
    {
        // TODO: ignore Host and Content-Length...
        oss << hdr << "\r\n";
    }
    oss << "\r\n";
    oss.write(static_cast<const char*>(body), bodyLength);
    return oss.str();
}

bool getHeaderValue(const std::vector<std::string> &headers, const std::string &headerName, std::string &value)
{
    value.clear();

    std::string toFind = headerName;
    upperCase(toFind);

    // find the requested header by name...
    for(auto &s : headers)
    {
        std::string::size_type pos = s.find(':');
        if (pos != std::string::npos)
        {
            std::string name = s.substr(0, pos-1);
            trim(name);
            upperCase(name);
            if (name == toFind)
            {
                // now return its value...
                value = s.substr(pos+1);
                trim(value);
                return true;
            }
        }
    }

    // name not found
    return false;
}

...

std::cout << "Connected to " << hostName << std::endl;

try
{
    std::string method, resource, hdr, data;
    std::string status, version, reason;
    std::vector<std::string> headers;
    int statusCode, rec;

    do
    {
        headers.clear();
        data.clear();

        // get user input

        std::cout << "Method > " << std::flush;
        if (!std::getline(std::cin, method))
            throw std::runtime_error("Error reading from stdin");
        upperCase(method);

        std::cout << "Resource > " << std::flush;
        if (!std::getline(std::cin, resource))
            throw std::runtime_error("Error reading from stdin");

        std::cout << "Extra Headers > " << std::flush;
        while (std::getline(std::cin, hdr) && !hdr.empty())
            headers.push_back(hdr);
        if (!std::cin)
            throw std::runtime_error("Error reading from stdin");

        std::cout << "Data > " << std::flush;
        // use Ctrl-Z or Ctrl-D to end the data, depending on platform...
        std::ios_base::fmtflags flags = std::cin.flags();
        std::cin >> std::noskipws;
        std::copy(std::istream_iterator<char>(std::cin), std::istream_iterator<char>(), std::back_inserter(data));
        if (!std::cin)
            throw std::runtime_error("Error reading from stdin");
        std::cin.flags(flags);
        std::cin.clear();

        // send request

        std::string request = makeRequest(hostName, method, resource, headers, data.c_str(), data.length());
        std::cout << "Sending request: << std::endl << request << std::endl;

        // TODO: reconnect to hostName if previous request disconnected...
        sendAll(connectSocket, request.c_str(), request.length());

        // receive response

        headers.clear();
        data.clear();

        // read the status line and parse it...
        status = readLine(connectSocket);
        std::cout << status << std::endl;    
        std::getline(std::istringstream(status) >> version >> statusCode, reason);
        upperCase(version);

        // read the headers...
        do
        {
            hdr = readLine(connectSocket);
            std::cout << hdr << std::endl;
            if (hdr.empty()) break;
            headers.push_back(hdr);
        }
        while (true);

        // The transfer-length of a message is the length of the message-body as
        // it appears in the message; that is, after any transfer-codings have
        // been applied. When a message-body is included with a message, the
        // transfer-length of that body is determined by one of the following
        // (in order of precedence):

        // 1. Any response message which "MUST NOT" include a message-body (such
        // as the 1xx, 204, and 304 responses and any response to a HEAD
        // request) is always terminated by the first empty line after the
        // header fields, regardless of the entity-header fields present in
        // the message.
        if (((statusCode / 100) != 1) &&
            (statusCode != 204) &&
            (statusCode != 304) &&
            (method != "HEAD"))
        {
            // 2. If a Transfer-Encoding header field (section 14.41) is present and
            // has any value other than "identity", then the transfer-length is
            // defined by use of the "chunked" transfer-coding (section 3.6),
            // unless the message is terminated by closing the connection.
            if (getHeaderValue(headers, "Transfer-Encoding", hdr))
                upperCase(hdr);
            if (!hdr.empty() && (hdr != "IDENTITY"))
            {
                std::string chunk;
                std::string::size_type oldSize, size;

                do
                {
                    chunk = readLine(connectSocket);

                    std::istringstream(chunk) >> std::hex >> size;
                    if (size == 0) break;

                    oldSize = data.size();
                    chunkData.resize(oldSize + size);
                    readAll(connectSocket, &data[oldSize], size);
                    std::cout.write(&data[oldSize], size);

                    readLine(connectSocket);
                }
                while (true);

                std::cout << std::endl;

                do
                {
                    hdr = readLine(connectSocket);
                    std::cout << hdr << std::endl;
                    if (hdr.empty()) break;
                    headers.push_back(hdr);
                }
                while (true);
            }

            // 3. If a Content-Length header field (section 14.13) is present, its
            // decimal value in OCTETs represents both the entity-length and the
            // transfer-length. The Content-Length header field MUST NOT be sent
            // if these two lengths are different (i.e., if a Transfer-Encoding
            // header field is present). If a message is received with both a
            // Transfer-Encoding header field and a Content-Length header field,
            // the latter MUST be ignored.
            else if (getHeaderValue(headers, "Content-Length", hdr))
            {
                std::string::size_type size;
                if ((std::istringstream(hdr) >> size) && (size > 0))
                {
                    data.resize(size);
                    readAll(connectSock, &data[0], size);
                    std::cout << data;
                }
            }

            // 4. If the message uses the media type "multipart/byteranges", and the
            // transfer-length is not otherwise specified, then this self-
            // delimiting media type defines the transfer-length. This media type
            // MUST NOT be used unless the sender knows that the recipient can parse
            // it; the presence in a request of a Range header with multiple byte-
            // range specifiers from a 1.1 client implies that the client can parse
            // multipart/byteranges responses.
            else if (getHeaderValue(headers, "Content-Type", hdr) &&
                    (hdr.compare(0, 10, "multipart/") == 0))
            {
                // TODO: extract 'boundary' attribute and read from
                // socket until the terminating boundary is reached...
            }

            // 5. By the server closing the connection.
            else
            {
                do
                {
                    rec = readSome(connectSocket, recvBuf, sizeof(recvBuf));
                    if (rec == 0) break;
                    data.append(recvBuf, rec);
                    std::cout.write(recvBuf, rec);
                }
                while (rec == sizeof(recvBuf));
            }
        }

        std::cout << std::endl;

        // use status, headers, and data as needed ...

        getHeaderValue(headers, "Connection", hdr);
        upperCase(hdr);

        if (version == "HTTP/1.0")
        {
            if (hdr != "KEEP-ALIVE")
                break;
        }
        else
        {
            if (hdr == "CLOSE")
                break;
        }
    }
    while (true);
}
catch (const std::exception &e)
{
    std::cerr << e.what() << std::endl;
}

closesocket(connectSocket);
std::cout << "Disconnected from " << hostName << std::endl;

std::system("pause");

Разве HTTP не забавен?:-) Это, безусловно, не полная реализация HTTP, но она должна помочь вам начать.Однако, как вы можете видеть, HTTP может быть довольно сложным для реализации с нуля, и он имеет много правил и ограничений, которым вы должны следовать.Вам лучше вообще не внедрять HTTP вручную.Существует множество сторонних HTTP-библиотек, доступных для C ++.Вместо этого используйте один из них и позвольте им справиться с тяжелой работой, чтобы вы могли сосредоточиться на своей собственной бизнес-логике.

...