c ++ socket.io客户端无法获取消息

时间:2018-03-29 06:43:08

标签: c++ websocket socket.io

我尝试使用c ++连接coincap.io API。作为库使用socket.io-client-cpp。它是连接的,但是来自服务器的任何消息。我的代码是:

    #include "socketio.h"

using namespace sio;

void OnMessage(sio::event &)
{
    std::cout << "get new msg" << std::endl;
}

std::mutex _lock;
std::condition_variable_any _cond;
bool connect_finish = false;

class connection_listener
{
    sio::client &handler;

public:

    connection_listener(sio::client& h) :
        handler(h)
    {
    }


    void on_connected()
    {
        _lock.lock();
        _cond.notify_all();
        connect_finish = true;
        _lock.unlock();

        std::cout << "sio is connect " << std::endl;

    }
    void on_close(client::close_reason const& reason)
    {
        std::cout << "sio closed " << std::endl;
        exit(0);
    }

    void on_fail()
    {
        std::cout << "sio failed " << std::endl;
        exit(0);
    }
};

int participants = -1;

socket::ptr current_socket;

void bind_events()
{
    current_socket->on("trades", sio::socket::event_listener_aux([&](std::string const& name, message::ptr const& data, bool isAck, message::list &ack_resp)
    {
        _lock.lock();
        std::cout << "get new msg" << std::endl;
        _lock.unlock();
    }));


}

socketio::socketio()
{

    std::cout << "socket.io test" << std::endl;

    sio::client h;
    connection_listener l(h);
    h.set_open_listener(std::bind(&connection_listener::on_connected, &l));
    h.set_close_listener(std::bind(&connection_listener::on_close, &l, std::placeholders::_1));
    h.set_fail_listener(std::bind(&connection_listener::on_fail, &l));

    h.connect("http://coincap.io");


    current_socket = h.socket();



    bind_events();


}


socketio::~socketio()
{
}

跑完后我进入控制台:

socket.io test
Error: No active session
[2018-03-28 23:30:53] [connect] Successful connection
[2018-03-28 23:30:54] [connect] WebSocket Connection 104.17.37.95:80 v-2 "WebSocket++/0.7.0" /socket.io/?EIO=4&transport=websocket&t=1522305053 101
sio is connect 

但没有得到任何“获取新信息”。

如果我在JS中测试socket.io,就像这样:

  var socket = io.connect('http://coincap.io');
        socket.on('trades', function (tradeMsg) {
            console.log(tradeMsg);
            document.getElementById('trade').innerHTML = JSON.stringify(tradeMsg)
        })

一切正常。谁知道我做错了什么?为什么不是听众的消息? 谢谢!

0 个答案:

没有答案