gpt4 book ai didi

c++ - MtGox API 和 websocketpp

转载 作者:行者123 更新时间:2023-11-30 00:52:01 32 4
gpt4 key购买 nike

我无法通过名为 websocketpp 的 WebSockets C++ 库从 MtGox API 获取信息:

#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>

#include <iostream>

typedef websocketpp::client<websocketpp::config::asio_client> client;

using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;

typedef websocketpp::config::asio_client::message_type::ptr message_ptr;

void on_open(websocketpp::connection_hdl hdl)
{
std::cout << "on_open \n";
}

void on_close(websocketpp::connection_hdl hdl)
{
std::cout << "on_close \n";
}

void on_message(client* c, websocketpp::connection_hdl hdl, message_ptr msg)
{
std::cout << msg->get_payload() << '\n';
}

int main()
{
client c;

try
{
c.init_asio();

c.set_open_handler(on_open);
c.set_close_handler(on_close);
c.set_message_handler(bind(&on_message, &c, ::_1, ::_2));

websocketpp::lib::error_code ec;
client::connection_ptr con = c.get_connection("ws://websocket.mtgox.com:80/mtgox?Currency=EUR", ec);
c.connect(con);

c.run();
}
catch (const std::exception& e)
{
std::cout << e.what() << std::endl;
}
catch (websocketpp::lib::error_code e)
{
std::cout << e.message() << std::endl;
}
catch (...)
{
std::cout << "other exception" << std::endl;
}
}

输出

[2013-11-18 23:10:10] [connect] Successful connection

[2013-11-18 23:10:14] [error] Server handshake response was invalid: Invalid HTTP status.

[2013-11-18 23:10:14] [disconnect] Failed: Invalid HTTP status.

在调试器中我看到“403 forbidden”错误,但我可以通过类似 http://www.websocket.org/echo.html 的服务使用它.

我已经尝试使用“ws://socketio.mtgox.com:80/mtgox?Currency=EUR”,但收到以下错误:

[2013-11-18 23:18:07] [connect] Successful connection

[2013-11-18 23:18:08] [error] error in handle_read_http_response: End of File

[2013-11-18 23:18:08] [disconnect] Failed: End of File

这段代码有什么问题?

最佳答案

MtGox 似乎在进行来源过滤。基于浏览器的 WebSocket 连接将自动发送一个原始 header ,其中包含运行脚本的域的值。由于这主要是针对运行可能未知的 Javascript 代码的浏览器的一项安全措施,因此默认情况下 WebSocket++ 不会发送原始 header 。

MtGox 似乎可以在我尝试过的任何来源上正常工作,只要设置了一个即可。据推测,他们使用它来将他们认为恶意的来源列入黑名单。您可以使用带有以下代码的 WebSocket++ 发送源 header (填写任何适合您的应用程序的源):

con->replace_header("Origin","http://www.example.com");

在请求与 endpoint::get_connection 的新连接之后,但在调用 endpoint::connect 之前运行它。

参见 http://en.wikipedia.org/wiki/Same-origin_policy有关此处使用的“同源策略”安全方法的更多详细信息。

关于c++ - MtGox API 和 websocketpp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20055987/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com