簡體   English   中英

通過C ++ Boost的VK API

[英]VK API throught C++ Boost

如何打開用於連接VK API的套接字,此代碼可與其他資源很好地配合使用,但可通過api.vk.com提供APPCRASH 在瀏覽器中,它可以與http ,因此應該在這里使用,問題不在'http`中,還是我錯了? 救命!

PS:Boost和VK API是我的新手,所以,如果可以的話,請詳細解釋,謝謝。

int main()
{
    boost::asio::io_service io_service;

    // Get a list of endpoints corresponding to the server name.
    tcp::resolver resolver(io_service);
    tcp::resolver::query query("api.vk.com", "http");
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

    // Try each endpoint until we successfully establish a connection.
    tcp::socket socket(io_service);
    boost::system::error_code error = boost::asio::error::host_not_found;
    socket.connect(*endpoint_iterator, error);
    return 0;
}

看起來APPCRASH可能是您在Windows事件日志中看到的東西。

由此,我形成了一個假設,即您可能正在Windows服務上下文中運行此代碼。

Windows服務默認情況下沒有網絡訪問權限。

這意味着DNS查找可能會失敗。 您將獲得一個例外,例如, resolve: Host not found (authoritative) 當我有意將域名更改為不存在的TLD時,這就是Linux控制台中發生的情況:

$ ./test
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::system::system_error> >'
  what():  resolve: Host not found (authoritative)
Aborted (core dumped)

因為您不處理異常或檢查錯誤,所以程序異常終止。

固定演示

注意:

  • 我選擇處理錯誤而不是異常。
  • 您無法遍歷查詢結果(僅使用第一個而不檢查其是否有效)
  • 與限制的Windows服務非常類似,Coliru也不允許回環適配器外部的網絡連接,因此它顯示適當的錯誤

生活在Coliru

#include <boost/asio.hpp>
#include <iostream>

using boost::asio::ip::tcp;

int main()
{
    boost::asio::io_service io_service;
    boost::system::error_code error = boost::asio::error::host_not_found;

    // Get a list of endpoints corresponding to the server name.
    tcp::resolver resolver(io_service);
    tcp::resolver::query query("api.vk.com", "http");
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query, error), last;

    if (!error) {

        // Try each endpoint until we successfully establish a connection.
        tcp::socket socket(io_service);

        for (;endpoint_iterator != last; ++endpoint_iterator) {
            socket.connect(*endpoint_iterator, error);
            if (!error) {
                std::cout << "Successfully connected to " << endpoint_iterator->endpoint() << "\n";
                break; // found working endpoint
            } else {
                std::cout << "Skipped " << endpoint_iterator->endpoint() << " - not connecting\n";
            }
        }
        return 0;
    } else {
        std::cout << error.message() << "\n";
        return 255;
    }
}

在我的系統上打印

Successfully connected to 87.240.131.97:80

我只是簡單地更改了DNS服務器即可使用: Successfully connected to 87.240.131.119:80

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM